Header Ads Widget

Develop Your Creative Skill with
Free Design Tutorials

Our blog helps to Provide Latest Tips and Tricks tutorials about Blogging
Business, SEO Tips, much more. this Blog and stay tuned to this
blog for further updates.

Factorial of a large number

Find Factorial of a Large Number

Getting Factorial of a large might be a tough task in other languages like c++, but java offers a big Integer class that can handle very large numbers. As Primitive data of 4 Byte can store only 2147483647. For calculations larger number than it, we will require a Bigger class than it. so java provides BigInteger class that can handle it properly.
BigInteger is Immutable in Java Means You cannot change the value once assigned to BigInteger Variable.

Factorial of a large number using BigInteger in Java

 class Courpedia {

 public static void main (String[] args) 
 Scanner sc = new Scanner(System.in);
  int t= sc.nextInt();
 for(int i=0;i<t;i++)
BigInteger fact= new BigInteger("1");
      long n=sc.nextLong();
fact=  fact.multiply(BigInteger.valueOf(n));

Big Integer class in java handles these large numbers very easily. It has various functions which we will discuss in our further blogs.
Now let us see how To get factorial of a large number in C++.

C++ does not have a Class like BigInteger as in Java. so we have to find the factorial of a large number using a different approach

 Factorial of a large number in C++

using namespace std;
void main() {
int T;
    while(T--) {
        int a[200];
        int rem;
        int i=0;
        int n,m=0;
        int temp;
        temp = n; 
            rem = temp%10;
            a[i] = rem;
            temp = temp/10;
         int h,x=0,ind=0;
             h = 0;
                 x = a[ind]*i + h;
                 a[ind] = x%10;
                 h = x/10;
                  a[ind] = h % 10;
                  h = h/10;

 You can compare the difference between the number of lines of code in Java solution and in C++ Solution.
here in c++, we are making an array to store all digits of the large number between 0 to 9.

Let us see how we can find the factorial of a large number in Python.
We don't have to bother about Large numbers in Python because it handles large numbers easily. Here is the code to find the factorial of the large numbers in Python.

Factorial of a large number in Python

##shortest solution in Python

T = int(input())
for i in range(T):
    n = int(input())
    fact = 1
    for i in range(1,n+1):
        fact = fact * i

There are Lots of other ways to do this you can try your own ways that may be more efficient than it. 

Practice this problem on geeks for geeks
Practice this problem on Codechef

-: You Might Like:-