top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to calculate factorial of higher numbers in C (greater then say 50)?

+2 votes
335 views

In c we can calculate upto 22 ! with long long but not beyond that so how can we calculate further using c program?
Please share program and algorithm with proper explanation?

posted Mar 13, 2016 by Shivam Kumar Pandey

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+4 votes
 
Best answer

The idea is to use the array of integers to store the factorial of such number like 50 or greater than 50. In this code i have used Dynamic programming as i have calculated all the factorials of a number starting from 1 to n-1 to calculate factorial of n, so in that way "memoization" is achieved.

for example:
for calculating factorial of 4: calculate all the factorials from 1 to 3, because now 6 remains in the array(factorial(3)=6 ) we will multiply it by 4 which yields 24 as 24 is greater than 10, 4(0'th position of 24) will be stored by the 21'th line " fact[j]=newNum%10;" and a carry number 2 will be stored by using 20'th line "carry=newNum/10;" , now array will have only 24 as the answer.

code:

#include <stdio.h>

int main()
{
    static int fact[100];
    int num;
    int i=1,j,l;
    int newNum,carry=0;
    scanf("%d",&num);

    if(num==0)
    {
        printf("%d",num);
        return 0;
    }

    fact[0]=1;
    for( l=1;l<=num;l++)
    {
        for(j=0;j<i;j++)
        {
            newNum=((fact[j]*l)+carry);
            carry=newNum/10;
            fact[j]=newNum%10;
            if(l==4)
                i=2;
            else if(l==5 || l==6)
                i=3;
        }

        if(l>6)
            i++;
        carry=0;
    }

    for(i=j;i!=0;i--)
        printf("%d",fact[i-1]);

}
answer Mar 16, 2016 by Shahsikant Dwivedi
Thanks Shashi !!! worked perfect
...