Search code examples
c++stlvectorfactorial

Why is the output containing - in this program?


This is a program for calculating factorial of a number and I store it in a vector. The Program works fine for inputs upto 30, but for n=40 and greater, it produces a weird output. eg.

input:

3

4

30

40

Output:

24

265252859812191058636308480000000

-190350521-236-6-6-5-745611269596115894272000000000

Where does this - sign come from?

#include<vector>
#include<cstdio>
#include<algorithm>
using namespace std;
vector<int> solve(int n){
        if(n==1){
                vector<int> ans;
                ans.push_back(1);
                return ans; 
        }
        vector<int> b=solve(n-1);
        int temp=0,x=0;
        for(int i=0;i<b.size();i++){
                x=b[i]*n+temp;
                b[i]=x%10;
                temp=x/10;
        }
        if(temp!=0)
            b.push_back(temp);
        return b;
}   
    int main(){
            int t,n,i;
            scanf("%d",&t);
            while(t--){
                    scanf("%d",&n);
                    vector<int> ans=solve(n);
                    for(int j=ans.size()-1;j>=0;j--)
                             printf("%d",ans[j]);
                    printf("\n");
            }
    }           

Solution

  • It's integer overflow. A fixed-size integer can only hold so large a value and then it overflows. You probably want to use an arbitrary precision integer library like GMP.

    Run your code with these changes and it will become obvious:

    vector<int> solve(int n)
    {
        if(n==1){
                vector<int> ans; 
                ans.push_back(1);
                return ans;
        }
        vector<int> b=solve(n-1);
        int temp=0,x=0;
        cout << "b.size=" << b.size() << ", n=" << n << endl;
        for(int i=0;i<b.size();i++){
                x=b[i]*n+temp;
                cout << "b[ " << i << "]=" << b[i] << ", temp= " << temp << ", x=" << x << endl;
                b[i]=x%10;
                temp=x/10;
        }
        if(temp!=0)
        {
            cout << "push_back(" << temp << ")" << endl;
            b.push_back(temp);
        }
        return b;
    }