Search code examples
carraysalgorithmfactorial

Calculation of factorial of large numbers in c using arrays


I am trying to calculate factorial of very large numbers in c like 100!..by dynamically allocating memory after calculating the number of digits in factorial: My code is:

int main()
{
    int n,q,i,j,z,t,d;
    float p=0.0;
    printf("Enter the number whose factorial is to be calculated:\n");
    scanf("%d",&n);
    //calculating number of digits
    for(j=2;j<=n;j++)
    p=p+log10(j);
    d=(int)p+1;
    printf("No of digits in the factorial are:%d\n",d);
    int *a;
    a=(int *)malloc(d*sizeof(int));//allocation of memory 
    a[0]=1;
    for(i=1;i<n;i++)//initialize array
    a[i]=0;
    p=0.0;
    for(j=2;j<=n;j++)
    {
        q=0;
        p=p+log10(j);
        z=(int)p+1;
        for(i=0;i<z;i++)
        {
           t=(a[i]*j)+q;
           q=t/10;
           a[i]=t%10;   
        }
    }
    printf("\n");
    for(i=d-1;i>=0;i--)
    {
        printf("%d",a[i]);
    }

    return 0;
}

Its providing correct answers upto 40! but not after that!What is wrong with my solution?


Solution

  • The problem is probably because of this loop:

    for(i=1;i<n;i++)//initialize array
    

    In the loop you clear the n - 1 entries of the allocated memory, but you allocate memory for d entries. If n - 1 is larger than d then you write outside the allocated memory, which causes undefined behavior. If n - 1 is smaller than d then you leave some memory uninitialized which also is undefined behavior when you access it.

    You should clear all of the memory, either by using your loop, by using memset or by using calloc when allocating.