Follow the steps below to solve the given problem:
Create an array res[] of MAX size where MAX is a number of maximum digits in output.
Initialize value stored in res[] as 1 and initialize res_size (size of 'res[]') as 1.
Multiply x with res[] and update res[] and res_size to store the multiplication result for all the numbers from x = 2 to n.
To multiply a number x with the number stored in res[],one by onemultiply x with every digit of res[].
To implement multiply function perform the following steps:
Initialize carry as 0.
Do following for i = 0 to res_size - 1
Find value of res[i] * x + carry. Let this value be prod.
Update res[i] by storing the last digit of prod in it.
Update carry by storing the remaining digits in carry.
Put all digits of carry in res[] and increase res_size by the number of digits in carry.
Below is the implementation of the above algorithm.
NOTE: In the below implementation, the maximum digits in the output are assumed as 500. To find a factorial of a much larger number ( > 254), increase the size of an array or increase the value of MAX. This can also be solved using Linked List instead of using res[] array which will not waste extra space.
C++
// C++ program to compute factorial of big numbers#include<iostream>usingnamespacestd;// Maximum number of digits in output#define MAX 500intmultiply(intx,intres[],intres_size);// This function finds factorial of large numbers// and prints themvoidfactorial(intn){intres[MAX];// Initialize resultres[0]=1;intres_size=1;// Apply simple factorial formula n! = 1 * 2 * 3// * 4...*nfor(intx=2;x<=n;x++)res_size=multiply(x,res,res_size);cout<<"Factorial of given number is \n";for(inti=res_size-1;i>=0;i--)cout<<res[i];}// This function multiplies x with the number// represented by res[].// res_size is size of res[] or number of digits in the// number represented by res[]. This function uses simple// school mathematics for multiplication.// This function returns the// new value of res_sizeintmultiply(intx,intres[],intres_size){intcarry=0;// Initialize carry// One by one multiply n with individual digits of res[]for(inti=0;i<res_size;i++){intprod=res[i]*x+carry;// Store last digit of 'prod' in res[]res[i]=prod%10;// Put rest in carrycarry=prod/10;}// Put carry in res and increase result sizewhile(carry){res[res_size]=carry%10;carry=carry/10;res_size++;}returnres_size;}// Driver programintmain(){factorial(100);return0;}
Java
// JAVA program to compute factorial// of big numbersclassGFG{// This function finds factorial of// large numbers and prints themstaticvoidfactorial(intn){intres[]=newint[500];// Initialize resultres[0]=1;intres_size=1;// Apply simple factorial formula// n! = 1 * 2 * 3 * 4...*nfor(intx=2;x<=n;x++)res_size=multiply(x,res,res_size);System.out.println("Factorial of given number is ");for(inti=res_size-1;i>=0;i--)System.out.print(res[i]);}// This function multiplies x with the number// represented by res[]. res_size is size of res[] or// number of digits in the number represented by res[].// This function uses simple school mathematics for// multiplication. This function may value of res_size// and returns the new value of res_sizestaticintmultiply(intx,intres[],intres_size){intcarry=0;// Initialize carry// One by one multiply n with individual// digits of res[]for(inti=0;i<res_size;i++){intprod=res[i]*x+carry;res[i]=prod%10;// Store last digit of// 'prod' in res[]carry=prod/10;// Put rest in carry}// Put carry in res and increase result sizewhile(carry!=0){res[res_size]=carry%10;carry=carry/10;res_size++;}returnres_size;}// Driver programpublicstaticvoidmain(Stringargs[]){factorial(100);}}// This code is contributed by Nikita Tiwari
Python
# Python program to compute factorial# of big numbersimportsys# This function finds factorial of large# numbers and prints themdeffactorial(n):res=[None]*500# Initialize resultres[0]=1res_size=1# Apply simple factorial formula# n! = 1 * 2 * 3 * 4...*nx=2whilex<=n:res_size=multiply(x,res,res_size)x=x+1print("Factorial of given number is")i=res_size-1whilei>=0:sys.stdout.write(str(res[i]))sys.stdout.flush()i=i-1# This function multiplies x with the number# represented by res[]. res_size is size of res[]# or number of digits in the number represented# by res[]. This function uses simple school# mathematics for multiplication. This function# may value of res_size and returns the new value# of res_sizedefmultiply(x,res,res_size):carry=0# Initialize carry# One by one multiply n with individual# digits of res[]i=0whilei<res_size:prod=res[i]*x+carryres[i]=prod%10# Store last digit of# 'prod' in res[]# make sure floor division is usedcarry=prod//10# Put rest in carryi=i+1# Put carry in res and increase result sizewhile(carry):res[res_size]=carry%10# make sure floor division is used# to avoid floating valuecarry=carry//10res_size=res_size+1returnres_size# Driver programfactorial(100)# This code is contributed by Nikita Tiwari.
C#
// C# program to compute// factorial of big numbersusingSystem;classGFG{// This function finds factorial// of large numbers and prints themstaticvoidfactorial(intn){int[]res=newint[500];// Initialize resultres[0]=1;intres_size=1;// Apply simple factorial formula// n! = 1 * 2 * 3 * 4...*nfor(intx=2;x<=n;x++)res_size=multiply(x,res,res_size);Console.WriteLine("Factorial of "+"given number is ");for(inti=res_size-1;i>=0;i--)Console.Write(res[i]);}// This function multiplies x// with the number represented// by res[]. res_size is size// of res[] or number of digits// in the number represented by// res[]. This function uses// simple school mathematics for// multiplication. This function// may value of res_size and// returns the new value of res_sizestaticintmultiply(intx,int[]res,intres_size){intcarry=0;// Initialize carry// One by one multiply n with// individual digits of res[]for(inti=0;i<res_size;i++){intprod=res[i]*x+carry;res[i]=prod%10;// Store last digit of// 'prod' in res[]carry=prod/10;// Put rest in carry}// Put carry in res and// increase result sizewhile(carry!=0){res[res_size]=carry%10;carry=carry/10;res_size++;}returnres_size;}// Driver CodestaticpublicvoidMain(){factorial(100);}}// This code is contributed by ajit
JavaScript
<script>// Javascript program to compute factorial of big numbers// This function finds factorial of large numbers// and prints themfunctionfactorial(n){letres=newArray(500);// Initialize resultres[0]=1;letres_size=1;// Apply simple factorial formula n! = 1 * 2 * 3 * 4...*nfor(letx=2;x<=n;x++)res_size=multiply(x,res,res_size);document.write("Factorial of given number is "+"<br>");for(leti=res_size-1;i>=0;i--)document.write(res[i]);}// This function multiplies x with the number // represented by res[].// res_size is size of res[] or number of digits in the // number represented by res[]. This function uses simple // school mathematics for multiplication.// This function may value of res_size and returns the // new value of res_sizefunctionmultiply(x,res,res_size){letcarry=0;// Initialize carry// One by one multiply n with individual digits of res[]for(leti=0;i<res_size;i++){letprod=res[i]*x+carry;// Store last digit of 'prod' in res[] res[i]=prod%10;// Put rest in carrycarry=Math.floor(prod/10);}// Put carry in res and increase result sizewhile(carry){res[res_size]=carry%10;carry=Math.floor(carry/10);res_size++;}returnres_size;}// Driver programfactorial(100);// This code is contributed by Mayank Tyagi</script>
PHP
<?php// PHP program to compute factorial // of big numbers// Maximum number of digits in output$MAX=500;// This function finds factorial of // large numbers and prints themfunctionfactorial($n){global$MAX;$res=array_fill(0,$MAX,0);// Initialize result$res[0]=1;$res_size=1;// Apply simple factorial formula // n! = 1 * 2 * 3 * 4...*nfor($x=2;$x<=$n;$x++)$res_size=multiply($x,$res,$res_size);echo"Factorial of given number is \n";for($i=$res_size-1;$i>=0;$i--)echo$res[$i];}// This function multiplies x with the number // represented by res[].// res_size is size of res[] or number of // digits in the number represented by res[]. // This function uses simple school mathematics // for multiplication. This function may value // of res_size and returns the new value of res_sizefunctionmultiply($x,&$res,$res_size){$carry=0;// Initialize carry// One by one multiply n with individual// digits of res[]for($i=0;$i<$res_size;$i++){$prod=$res[$i]*$x+$carry;// Store last digit of 'prod' in res[] $res[$i]=$prod%10;// Put rest in carry$carry=(int)($prod/10);}// Put carry in res and increase // result sizewhile($carry){$res[$res_size]=$carry%10;$carry=(int)($carry/10);$res_size++;}return$res_size;}// Driver Codefactorial(100);// This code is contributed by chandan_jnu?>
Output
Factorial of given number is
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
Time Complexity: O(N log (N!)), where O(N) is for loop and O(log N!) is for nested while loop Auxiliary Space: O(max(digits in factorial))
Find the Factorial of a large number using Basic BigInteger
This problem can be solved using the below idea:
Big Integer can also be used to calculate the factorial of large numbers.
Illustration:
N = 5
ans = 1
At i = 2: ans = ans x i = 1 x 2 = 2 At i = 3: ans = ans x i = 2 x 3 = 6 At i = 4: ans = ans x i = 6 x 4 = 24 At i = 5: ans = ans x i = 24 x 5 = 120
Hence factorial of N is 120
Follow the steps below to solve the given problem:
Declare a BigInteger f with 1and perform the conventional way of calculating factorial
Traverse a loop from x = 2 to N and multiply x with f and store the resultant value in f
Below is the implementation of the above idea :
C++
// C++ program to find large// factorials using BigInteger#include<bits/stdc++.h>usingnamespacestd;#define ull unsigned long long// Returns Factorial of Nullfactorial(intN){// Initialize resultullf=1;// Or BigInt 1// Multiply f with 2, 3, ...Nfor(ulli=2;i<=N;i++)f*=i;returnf;}// Driver methodintmain(){intN=20;cout<<factorial(N)<<endl;}// This code is contributed by phasing17
Java
// Java program to find large// factorials using BigIntegerimportjava.math.BigInteger;importjava.util.Scanner;publicclassExample{// Returns Factorial of NstaticBigIntegerfactorial(intN){// Initialize resultBigIntegerf=newBigInteger("1");// Or BigInteger.ONE// Multiply f with 2, 3, ...Nfor(inti=2;i<=N;i++)f=f.multiply(BigInteger.valueOf(i));returnf;}// Driver methodpublicstaticvoidmain(Stringargs[])throwsException{intN=20;System.out.println(factorial(N));}}
Python
# Python3 program to find large# factorials# Returns Factorial of Ndeffactorial(N):# Initialize resultf=1# Multiply f with 2, 3, ...Nforiinrange(2,N+1):f*=ireturnf;# Driver methodN=20;print(factorial(N));# This code is contributed by phasing17
C#
// C# program to find large// factorials using BigIntegerusingSystem;usingSystem.Collections.Generic;usingSystem.Numerics;publicclassExample{// Returns Factorial of NstaticBigIntegerfactorial(intN){// Initialize resultBigIntegerf=newBigInteger(1);// Or BigInteger.ONE// Multiply f with 2, 3, ...Nfor(inti=2;i<=N;i++)f=BigInteger.Multiply(f,newBigInteger(i));returnf;}// Driver methodpublicstaticvoidMain(string[]args){intN=20;Console.WriteLine(factorial(N));}}// This code is contributed by phasing17
JavaScript
// JavaScript program to find large// factorials using BigInteger// Returns Factorial of Nfunctionfactorial(N){// Initialize resultletf=BigInt(1);// Or BigInt 1// Multiply f with 2, 3, ...Nfor(vari=2;i<=N;i++)f*=BigInt(i);returnf;}// Driver methodletN=20;console.log(factorial(N));// This code is contributed by phasing17
Output
2432902008176640000
Time Complexity: O(N) Auxiliary Space: O(1)
Find Factorial of a number using Linked List :-
So the basic idea is to multiply the next number ranging between 2 to N with the data stored in the current Node and also maintain a carry just like the array approach. And then move on to the next node.
Let's break it down into following steps :
Initially we'll create 1 single node containing 1 in it.
Then initialized i of a for loop with 2.
And for each value of i up till N, we'll call a function multiply which takes 2 parameter, head of the list and value of i.
And perform the below operation (See the image)
Operation
The above operation will be carried out till our temp pointer becomes NULL.
Now there are further 2 cases , The multiplication of i with the node's data :
Doesn't exceed 1 digit
Exceeds 1 digit
If the multiplication of current node's data with i - Exceeds 1 digit, then we won't be storing it into a single node. Rather, we'll be storing each digit into a single node. And if it doesn't then we'll simply replace current node's data with it.
So, by above explanation we can conclude and form the following steps to solve this problem :
Algorithm:
Find value of : node's data * i + carry. Store it in a variable 'prod'.
Initialize 2 pointers let's say prev and temp on the current node and Update the current node's value by storing the last digit of the 'prod'
Update carry by storing the remaining digits in carry (excluding the last digit)
Now, bring prev ptr on temp and move temp to the next node (if any) and then again perform, the previous steps until the carry becomes 0 or the temp ptr becomes NULL.
Once the temp pointer reaches the NULL there is a possibility that carry is still not 0. So, until carry becomes 0 we have to again perform the same steps by creating a new node for every remaining digit.
See the image below for the Dry run of above steps :
Just like this, we'll do for the remaining digits, and each of the digit will be stored in a single node.
Code :
C++
#include<bits/stdc++.h>usingnamespacestd;//* Node ClassclassNode{public:intdata;Node*prev;Node(intn){data=n;prev=NULL;}};//* Function to perform desired operationvoidMultiply(Node*head,inti){Node*temp=head,*prevPtr=head;// Temp variable for keeping headintcarry=0;//* Perform operation until temp becomes NULLwhile(temp!=NULL){intprod=temp->data*i+carry;temp->data=prod%10;//* Stores the last digitcarry=prod/10;prevPtr=temp;//* Change Linkstemp=temp->prev;//* Moving temp to next node}//* If carry is greater than 0 then we create new nodes//* to store remaining digits.while(carry!=0){prevPtr->prev=newNode((int)(carry%10));carry/=10;prevPtr=prevPtr->prev;}}//* Using head recursion to print the linked list's data in reversevoidprint(Node*head){if(head==NULL)return;print(head->prev);cout<<head->data;// Print linked list in reverse order}// Driver codeintmain(){intn=100;Node*head=newNode(1);// Create a node and initialise it by 1for(inti=2;i<=n;i++)Multiply(head,i);// Run a loop from 2 to n and// multiply with head's icout<<"Factorial of "<<n<<" is : \n";print(head);// Print the linked listcout<<endl;return0;}
Java
//* Node ClassclassNode{publicintdata;publicNodeprev;publicNode(intn){data=n;prev=null;}}//* Function to perform desired operationclassMain{publicstaticvoidMultiply(Nodehead,inti){Nodetemp=head;NodeprevPtr=head;// Temp variable for keeping headintcarry=0;//* Perform operation until temp becomes nullwhile(temp!=null){intprod=temp.data*i+carry;temp.data=prod%10;//* Stores the last digitcarry=prod/10;prevPtr=temp;//* Change Linkstemp=temp.prev;//* Moving temp to next node}//* If carry is greater than 0 then we create new nodes//* to store remaining digits.while(carry!=0){prevPtr.prev=newNode((int)(carry%10));carry/=10;prevPtr=prevPtr.prev;}}//* Using head recursion to print the linked list's data in reversepublicstaticvoidprint(Nodehead){if(head==null)return;print(head.prev);System.out.print(head.data);// Print linked list in reverse order}// Driver codepublicstaticvoidmain(String[]args){intn=100;Nodehead=newNode(1);// Create a node and initialize it by 1for(inti=2;i<=n;i++)Multiply(head,i);// Run a loop from 2 to n and multiply with head's iSystem.out.println("Factorial of "+n+" is : ");print(head);// Print the linked listSystem.out.println();}}// by phasing17
Python
# Node ClassclassNode:def__init__(self,n):self.data=nself.prev=None# Function to perform desired operationdefMultiply(head,i):temp=headprevPtr=headcarry=0# Perform operation until temp becomes NonewhiletempisnotNone:prod=temp.data*i+carrytemp.data=prod%10# Stores the last digitcarry=prod//10prevPtr=temp# Change Linkstemp=temp.prev# Moving temp to the next node# If carry is greater than 0, create new nodes to store remaining digitswhilecarry!=0:prevPtr.prev=Node(carry%10)carry=carry//10prevPtr=prevPtr.prev# Using recursion to print the linked list's data in reversedefprint_list(head):ifheadisNone:returnprint_list(head.prev)print(head.data,end="")# Print linked list in reverse order# Driver codedefmain():n=100head=Node(1)# Create a node and initialize it by 1foriinrange(2,n+1):Multiply(head,i)# Run a loop from 2 to n and multiply with head's iprint("Factorial of",n,"is : ")print_list(head)# Print the linked listprint()main()
C#
usingSystem;// Node ClasspublicclassNode{publicintdata;publicNodeprev;publicNode(intn){data=n;prev=null;}}// Function to perform desired operationpublicclassProgram{publicstaticvoidMultiply(Nodehead,inti){Nodetemp=head;NodeprevPtr=head;intcarry=0;// Perform operation until temp becomes nullwhile(temp!=null){intprod=temp.data*i+carry;temp.data=prod%10;carry=prod/10;prevPtr=temp;temp=temp.prev;}// If carry is greater than 0 then we create new nodes// to store remaining digits.while(carry!=0){prevPtr.prev=newNode((int)(carry%10));carry/=10;prevPtr=prevPtr.prev;}}// Using head recursion to print the linked list's data in reversepublicstaticvoidPrint(Nodehead){if(head==null)return;Print(head.prev);Console.Write(head.data);// Print linked list in reverse order}// Driver codepublicstaticvoidMain(){intn=100;Nodehead=newNode(1);// Create a node and initialize it by 1for(inti=2;i<=n;i++)Multiply(head,i);// Run a loop from 2 to n and// multiply with head's iConsole.WriteLine("Factorial of "+n+" is : ");Print(head);// Print the linked listConsole.WriteLine();}}
JavaScript
// Node ClassclassNode{constructor(n){this.data=n;this.prev=null;}}// Function to perform desired operationfunctionMultiply(head,i){lettemp=head;letprevPtr=head;letcarry=0;// Perform operation until temp becomes nullwhile(temp!==null){letprod=temp.data*i+carry;temp.data=prod%10;// Stores the last digitcarry=Math.floor(prod/10);prevPtr=temp;// Change Linkstemp=temp.prev;// Moving temp to the next node}// If carry is greater than 0, create new nodes to store remaining digitswhile(carry!==0){prevPtr.prev=newNode(carry%10);carry=Math.floor(carry/10);prevPtr=prevPtr.prev;}}// Using recursion to print the linked list's data in reversefunctionprint(head){if(head===null)return;print(head.prev);process.stdout.write(head.data.toString());// Print linked list in reverse order}// Driver codefunctionmain(){constn=100;consthead=newNode(1);// Create a node and initialize it by 1for(leti=2;i<=n;i++)Multiply(head,i);// Run a loop from 2 to n and multiply with head's iconsole.log("Factorial of "+n+" is : ");print(head);// Print the linked listconsole.log();}main();
Output
Factorial of 100 is :
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
Time Complexity : O(N²) Space Complexity : O(digits in factorial)
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.