Large number factorial algorithm
Original link
Large number factorial algorithm
A few days ago my friend asked me a question: "How does the factorial of 10000 count?" "I was a little confused at the time," 10000 "the number is too large, regardless of what data type to save the results will overflow. What can I do about it? At a time helpless. And then despised by a meal. Later by friends reminded, only to realize, finally know how to achieve, the original is to use an array to simulate the number, so no matter how large the number of results, as long as the length of the array can be expressed, with this method can be large data operation. It seems to be quite useful. I use it to implement the program, if useful to the place can also draw on. (At least you can take it to despise others ^_^)
First, define a long enough array.
Taking the factorial of 10000 as an example, the final result is 35,660 bits in length, so we define an array of 40,000 members.
int result[40000];
The core idea is to save the numbers on each of the calculation results to an array member, for example:
Save the 124 to the array, and the result should be
RESULT[0] 4
RESULT[1] 2
RESULT[2] 1
This certainly is no problem, an int type data holds a number less than 10 is absolutely not overflow. But it's a little tricky to deal with.
The whole array is treated as a number, and when multiplied by a number, it is necessary to multiply each bit with the multiplier and add the previous carry. The arithmetic is the same as the primary mathematics, the product of the bits is the current position should be represented by the number, more than 10 need to carry. Because the multiplier cannot be greater than 10000, the multiplier is no more than 100000 when multiplied by a book that is less than 10, plus the previous digit has no problem keeping the result with an int type of data. The wording is as follows:
int result = result[x] * multiplier + rounding;
Each bit is computed, and the single digit of the result is taken out onto the array element:
RESULT[X] = result%10;
The next task is to calculate the rounding:
Rounding = result/10;
So one of them computes the entire array once, and finally possibly the carry, and in the same way, splits the value of the carry into a single number and puts it into the corresponding array element.
Finally output the results, from the highest bit of the digital printing once again OK. The complete program is as follows and is debugged under VC6.0.
#include <stdio.h>intMain () {intcarry,n,j; inta[40001]; intDigit; intTemp,i; while(SCANF ("%d", &n)! =EOF) {a[0]=1;d igit=1; for(i=2; i<=n; i++) { for(carry=0, j=1; j<=digit; ++j) {Temp=a[j-1]*i+carry; A[j-1]=temp%Ten; Carry=temp/Ten; } while(carry) {//digit++;a[++digit-1]=carry%Ten; Carry/=Ten; } } for(intK=digit; k>=1; --k) printf ("%d", a[k-1]); printf ("\ n"); printf ("length=%d\n", digit); } return 0;}
View Code
Large number algorithm