Factorial of a large number

#include
using namespace std;

int multiply(int x, long int res[],long int res_size)
{
int carry = 0;
for (int i=0; i<res_size; i++)
{
int prod = res[i] * x + carry;
res[i] = prod % 10;
carry = prod/10;
}
while (carry)
{
res[res_size] = carry%10;
carry = carry/10;
res_size++;
}
return res_size;
}
void factorial(int n)
{
long int i;
long int res[501];
res[0]=1;
long int res_size=1;
for(i=2;i<=n;i++)
res_size=multiply(i,res,res_size);
for (int i=res_size-1; i>=0; iā€“)
cout << res[i];
}
int main() {
int n;
cin>>n;
factorial(n);
return 0;
}

What is the problem?This code is giving run error for testcase1

Hi @shivansh.sm1
See you are getting run time error because of the size of res array. In the question it is given that n < 500, So you have to make res as res[1000] to avoid run error.

Here is your corrected code :

1 Like