Abstract: This article provides some simple procedures for calculating factorial, which are also the calculation factorial program written by beginners in many c-language dialects. Although it cannot calculate the big number factorial correctly, it still has many correct ideas. Let's start with an error and start a long and fun journey to explore the path of big data factorial computing... Program 1: the most direct calculation of factorial Program
#include "stdio.h"#include "stdlib.h" int main(int argc, char* argv[]){ long i,n,p; printf("n=?"); scanf("%d",&n); p=1; for (i=1;i<=n;i++) p*=i; printf("%d!=%d/n",n,p); return 0;}
Program 2, a little more complex, uses recursion, a program written by C ++ beginners
#include <iostream.h> long int fac(int n); void main() { int n; cout<<"input a positive integer:"; cin>>n; long fa=fac(n); cout<<n<<"! ="<<fa<<endl; } long int fac(int n) { long int p; if(n==0) p=1; else p=n*fac(n-1); return p; }
The program commented that these two programs are correct in the calculation of the number of less than 12, but when n> 12, the calculation result of the program is completely wrong. From the algorithm alone, the program is not wrong, but where did the program go wrong? It seems that the author does not realize that a long integer can represent a very limited range. When N> = 13, the calculation result overflows. If n> = 13, overflow occurs in the C language and integer multiplication, and no exception or warning is given. Since the integer range is limited, can we use a data type with a larger range for calculation? This is a good idea. So what kind of data type should we choose? Some people think of the double type and replace the long type in program 1 with the double type. The result is as follows:
#include "stdio.h"#include "stdlib.h" int main(int argc, char* argv[]){ double i,n,p; printf("n=?"); scanf("%lf",&n); p=1.0; for (i=1;i<=n;i++) p*=i; printf("%lf!=%.16g/n",n,p); return 0;}
Run this program, compare the calculation result with the Windows Calculator, and find that the result is correct within the error range when the value is less than 170. However, when n> = 171, the result cannot be correctly displayed. Why? Similar to program 1, data overflows, that is, the range that the calculation result can represent beyond the data type. It seems that the data types provided by C language cannot meet the needs of big data factorial calculation. Therefore, there are only two methods. 1. Find a class library that can represent and process large numbers of operations. 2. Storage and calculation of large numbers by yourself. Method 1 is not covered in this article. Subsequent articles in this series will focus on method 2.