i came across the following program for calculating large factorials(numbers as big as 100).. can anyone explain me the basic idea used in this algorithm??
I need to know just the mathematics implemented in calculating the factorial.
#include <cmath>
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
unsigned int d;
unsigned char *a;
unsigned int j, n, q, z, t;
int i,arr[101],f;
double p;
cin>>n;
p = 0.0;
for(j = 2; j <= n; j++)
p += log10(j);
d = (int)p + 1;
a = new unsigned char[d];
for (i = 1; i < d; i++)
a[i] = 0; //initialize
a[0] = 1;
p = 0.0;
for (j = 2; j <= n; j++)
{
q = 0;
p += log10(j);
z = (int)p + 1;
for (i = 0; i <= z/*NUMDIGITS*/; i++)
{
t = (a[i] * j) + q;
q = (t / 10);
a[i] = (char)(t % 10);
}
}
for( i = d -1; i >= 0; i--)
cout << (int)a[i];
cout<<"\n";
delete []a;
return 0;
}
Note that
so that
This is important because if
kis a positive integer then the ceiling oflog(k)is the number of digits in the base-10 representation ofk. Thus, these lines of code are counting the number of digits inn!.Then, these lines of code allocate space to hold the digits of
n!:Then we just do the grade-school multiplication algorithm
The outer loop is running from
jfrom2tonbecause at each step we will multiply the current result represented by the digits inabyj. The inner loop is the grade-school multiplication algorithm wherein we multiply each digit byjand carry the result intoqif necessary.The
p = 0.0before the nested loop and thep += log10(j)inside the loop just keep track of the number of digits in the answer so far.Incidentally, I think there is a bug in this part of the program. The loop condition should be
i < znoti <= zotherwise we will be writing past the end ofawhenz == dwhich will happen for sure whenj == n. Thus replaceby
Then we just print out the digits
and free the allocated memory