In: Computer Science
In C++. Write a program that uses array to calculate the factorial of a reasonable large number (say, up to 2,000).
Program:
#include<iostream>
using namespace std;
#define size 5737 // It produce upto 5737 digits
void factorial(int n); // Function prototype
int fact(int i, int array[], int arraySize); // Function prototype
int main()
{
int n; // variable declaration
cout<<"Enter a number(upto 2000): ";
cin>>n; // Accept n value
cout<<"Factorial of "<<n<<" is:"<<endl;
factorial(n); // calling function to find the factorial
return 0;
}
void factorial(int n) // calling function to find factorial
{
int array[size];
array[0] = 1;
int arraySize = 1;
for (int i=2; i<=n; i++)
arraySize = fact(i, array, arraySize); // recusive calling to find output size
for (int j=arraySize-1; j>=0; j--)
cout << array[j]; // print factorial using array
cout<<endl;
}
int fact(int i, int array[], int arraySize) // calling function to find output size
{
int check = 0;
for (int k=0; k< arraySize; k++)
{
int m = array[k] * i + check;
array[k] = m % 10;
check = m/10;
}
while (check)
{
array[arraySize] = check%10;
check = check/10;
arraySize++;
}
return arraySize;
}
Output: