What's wrong?? -- fctrl2

#include<stdio.h>
int main()
{
int t,n,f=1;
scanf("%d",&t);
int arr[t];
for(int i=1;i<=t;i++)
{
scanf("%d",&arr[i]);
if(i==t)
break;
}
printf("\n");
for(int j=1;j<=t;j++){
for(int k=1;k<=arr[j];k++)
{
f*=k;
}
printf("%d\n",f );
f=1;
}

}

Let the number whose factorial we need to find be 13. 13! equals 6227020800 which can be written as 6.210^9. You are storing it in an int variable ‘f’ whose maximum value can be equal be to 2,147,483,647 ~ 210^9. Thus you might be getting a wrong answer because of integer overflow condition.

i changed the data type to long long, still getting the answer wrong.

https://discuss.codechef.com/questions/7349/computing-factorials-of-a-huge-number-in-cc-a-tutorial

1 Like

Even after using long long there will be an overflow condition for factorial of 23. Here you need to store the answer in a different way like using an array to store the digits of the answer rather than just storing it in a primitive datatype.

1 Like

Dear hardy_971 ,

int cannot store factorial of large numbers.

So there are 2 methods of doing it.

1)big integer in c++.This is my accepted code.

https://www.codechef.com/viewsolution/15890382

#include<bits/stdc++.h> // includes every standard library file
#include<boost/multiprecision/cpp_int.hpp>
namespace mp = boost::multiprecision;
using namespace std;
#define ll long long
#include

int main()
{

int t;
cin>>t;
while(t--)
{
    mp::cpp_int n,f=1,i;
    cin>>n;
    
    for(i=1;i<=n;i++)
    f=f*i;
    
    cout << f<<endl;
}

}

2)Another way is by see this link

https://discuss.codechef.com/questions/7349/computing-factorials-of-a-huge-number-in-cc-a-tutorial