Tuesday, October 4, 2011

C program to evaluate factorials upto 100 (100!)


Well, this program can be extended to find values of factorial of numbers more than 100. It uses an array of size equal to maximum no. of digits of factorial value(100 in this case). (We can only find factorial of upto 13 with unsigned long, after that we are left with no choice, hence the program solves this problem)

#include<stdio.h>
int fact[160];
main()
{
    int n,carry,i,size;;
    carry=0;
    size=159;
    fact[0]=1;
    scanf("%d",&n);
    while(n>0)
    {
        i=0;
        do
        {
            fact[i]*=n;
            fact[i]+=carry;
            carry=fact[i]/10;
            fact[i]=fact[i]%10;
        }while(i++ != 158);

        n--;
    }

    for(i=159;i>=0;i--)
    {
        if(fact[i]==0)
        size--;
        else
        break;
    }
    for(i=size;i>=0;i--)
    printf("%d",fact[i]);
    printf("\n");


}

No comments:

Post a Comment