Q:

C++ program to find factorial of large numbers using array

0

C++ program to find factorial of large numbers using array

In this program basically we multiply the number from 1 to the number and every time we store the value in array from left to right for e.g. ( if I want to store 129 into the array I will store it as 921 it will be easily to do calculations this way).

  • Initially 1 will be stored in the ar[] and the ar_size will also be 1
  • then it will enter int the of x from x=2 to x=number multiply x*ar[]
  • and update the ar[]. To store the value in ar[] following operation will take place the loop runs from i=0 to ar_size and we will store the last digit int the variable p and update the ar[] and the rest of the digits will be stored in c and in the next loop we will have to store digit by digit in ar[].

Let’s take an example of 5

For x=2
ar[]=1, ar_size=1
p=2*ar[]=2*1 ,c=0 
ar[]=2 ,c=0

For x=3
ar[]=2,ar_size=1
p=3*ar[]=3*2 ,c=0
ar[]=6 ,c=0

For x=4
ar[]=6,ar_size=1
p=4*ar[]=4*6=24 ,c=2
ar[]=4, c=2        ar[]=42,c=0

For x=5
ar[]=42,c=0
p=5*4=20
ar[]=0 ,c=2    
p=5*2+c=12
ar[]=021

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Consider the program:

#include<iostream>
using namespace std;

#define size 10000 

int fact(int x, int ar[], int ar_size);

void factorial(int n)
{
	int ar[size];
	ar[0] = 1;
	int ar_size = 1;
	
	for (int x=2; x<=n; x++)
		ar_size = fact(x, ar, ar_size);
	
	for (int i=ar_size-1; i>=0; i--)
		cout << ar[i];	

	cout<<endl;
}

int fact(int x, int ar[], int ar_size)
{
	int c = 0; 
	for (int i=0; i< ar_size; i++)
	{   int p = ar[i] * x + c;
		ar[i] = p % 10; 
		c = p/10; 
	}

	while (c)
	{
		ar[ar_size] = c%10;
		c = c/10;
		ar_size++;
	}
	return ar_size;
	
}
int main()
{

	int n;

	cout<<"Enter an integer number: ";
	cin>>n;

	cout<<"Factorial of "<<n<<" is:"<<endl;
	factorial(n);

	return 0;
}

Output

First run:
Enter an integer number: 20 
Factorial of 20 is: 
2432902008176640000 


Second run:
Enter an integer number: 250
Factorial of 250 is:
3232856260909107732320814552024368470994843717673780666747942427112823747555111209488817915371028199450928507353189432926730931712808990822791030279071281921676
5272401892647332180411862610068329253651336789390895699357135301750405131787600772479330654023390061648255522488194365725860573992226412548329822048491377217766
5064127685880715312897877767295191399084437747870258917297325515028324178732065818848206247858265980884882554880000000000000000000000000000000000000000000000000
0000000000000 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now