gospelslide
gospelslide

Reputation: 179

Bug in the code to calculate factorials upto 100?

#include<stdio.h>
int main()
{
int t,carry=0,i,j=1,index,x,no=1;
int c;
scanf("%d",&t);
int a[200]={0};
a[0]=1;
for(i=1;i<=t;i++)
{
    index=0;
    no=j;
    carry=0;
    while(index<no)
    {
        x=a[index]*i+carry;
        a[index]=x%10;
        j++;
        if(x!=0)
            carry=x/10;
        index++;
    }
    while(carry!=0)
    {
        a[index]=carry%10;
        j++;
        carry/=10;
        index++;
    }   
}
j=199;
printf("\n");
while(j>=0)
{
    printf("%d",a[j]);
    j--;
}
scanf("%d",&c);
return 0;
}

This code gives me the right answer till 8 factorial,for 9 and above the answer I get is 362230 What is the reason??? Btw I know it can be implemented easily in Java or other languages but I want to use this method so please don't suggest that.I can't find the bug.The code runs in gcc but gives error on ideone,don't know why. Help!

Upvotes: 2

Views: 365

Answers (1)

Wintermute
Wintermute

Reputation: 44063

Leaving aside style questions and the fact that storing a big integer in decimal digits is rather wasteful, the problem is that you never reset j. Because of this, the loop

while(index<no)
{
    x=a[index]*i+carry;
    a[index]=x%10;
    j++;
    if(x!=0)
        carry=x/10;
    index++;
}

means that j will at least double in every multiplication, and after eight of them, j will be larger than the 200 elements of the array in which you store the digits of the factorial. Then, with

no=j;

the

while(index<no)
{
    x=a[index]*i+carry;
    a[index]=x%10;

bit both reads and writes beyond the bounds of the array.

The least invasive way to fix this is to

while(carry!=0)
{
    a[index]=carry%10;
    j++;
    carry/=10;
    index++;
}

j = index;    // <--- add this here.

Note that this leaves you with essentially dead code, though; counting j up in the loops serves no purpose.

Upvotes: 2

Related Questions