Wednesday, March 23, 2011

WAP to Calculate The Factorial of BIG NUmber(Obvious Integer,Long) That Can't Fit In Memory at a time

In order to learn this big number arithmetic lets take an example of calculating factorial of big numbers

24 = 4!
120 = 5! 8-bit unsigned int
720 = 6!
5040 = 7!
40320 = 8! 16-bit unsigned int(not exactly)
362880 = 9!
39916800 = 11!

479001600 = 12! 32-bit unsigned (this is the maximum number that can fit in the integer of size of 32 bit) =2147483647

87178291200 = 14!
6402373705728000 = 18!
121645100408832000 = 19!
2432902008176640000 = 20! 64-bit unsigned
51090942171709440000 = 21!
8222838654177922817725562880000000 = 31!
263130836933693530167218012160000000 = 32
295232799039604140847618609643520000000 = 34! 128-bit unsigned

Now if we have to calculate something like 100! then it not possible to do with inbuilt int(4 byte) long long int (8 byte)Now, the maximum number that we can store in an unsigned 32 bit integer is 2 ^ 32 - 1 and in an unsigned 64 bit integer is 2 ^ 64 - 1. Something like 100!('!' is the notation for factorial) has over 150 decimal digits. The data types mentioned earlier can store numbers having at most 9 and 19 decimal digits respectively. So, we need to find a way to store the 150+ digits that we will get as the answer. The simplest data structure that we can use is an integer array of size of about 200 to be on the safe side.
#include
#include
void factorial(int n)
{
int digit[160];
int m, carry,d,i,last;
for(i=0;i<160;i++) digit[i]=0; digit[0]=1; last=0; for(m=1;m<=n;m++) { carry=0; for(i=0;i<=last;i++) {d=digit[i]*m+carry; digit[i]=d%10; carry=d/10; } while(carry>0)
{
last=last + 1;
digit[last]=carry%10;
carry=carry/10;
}
}

for(i=last;i>=0;i--)
printf("%d",digit[i]);
printf("\n");

}
int main()
{
factorial(100);
int n=pow(2,32)-1;
printf(" %d ", n);

}

Factorial of 100 =93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

Run Here https://ideone.com/fgaSP

C++ Code Recursive Version

#include
#include

int max = 5000;

void display(int arr[]){
int ctr = 0;
for (int i=0; i<=0; --i){
arr[i] = (arr[i] * n) + carry;
carry = arr[i]/10;
arr[i] %= 10;
}
factorial(arr,n-1);
}

int main(){
int *arr = new int[max];
std::memset(arr,0,max*sizeof(int));
arr[max-1] = 1;
int num=100;
std::cout<<"Enter the number: ";

std::cout<<"factorial of "<<<"is :\n";
factorial(arr,num);
display(arr);
delete[] arr;
return 0;
}

Run Here https://ideone.com/R7Q0F

I suggest you people to go through this article http://www.codeproject.com/KB/recipes/factorial.aspx 

5 Fast Way to Computer Big Factorial https://www.luschny.de/math/factorial/FastFactorialFunctions.htm

No comments :