huge factorial

closed account (1vf9z8AR)
What is wrong with my program? The answer is little off.

This is for calculating factorial

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
  #include<iostream>
using namespace std;
int main()
{
    int t;
    cin>>t;
    while(t>0)
    {
        int n;
        cin>>n;
        int str[200];
        str[0]=1;
        for(int i=1;i<200;i++)
            str[i]=0;
        int i=0;
        int carry=0,pos=0;
        while(n>0)
        {
            pos=0;
            carry=0;
            while(pos<=i)
            {
                int x=(str[pos]*n)+carry;
                carry=x/10;
                str[pos]=x%10;
                pos++;
            }
            while(carry>0)
            {
            	str[pos]=carry%10;
                carry/=10;
                i++;
                pos++;
            }
            n--;
        }
        for(int j=i;j>=0;j--)
            cout<<str[i];
        cout<<endl;
        t--;
    }
}
Why not use a recursive function? It may be slower for bigger numbers but its less code

1
2
3
4
5
6
7
int factorial(int n)
{
    if(n > 1)
        return n * factorial(n - 1);
    else
        return 1;
}
Take a look at line 38.

After fixing that. Try making your program even better by allowing arbitrarily large inputs instead of only allowing integers up to 200 digits.
closed account (1vf9z8AR)
@kingkush

but 100! won't fit in int
Topic archived. No new replies allowed.