Google Add

Search

Program to Find Factorial of 100 (Big Numbers) in Java

Write a program to find factorial of 100 in java. How to find factorial of a big numbers in java.  Factorial of a number greater than 20 can't be stored even in a 64 bit long long int. So how to solve this problem.

Let's quickly understand what is factorial.

Factorial of a non-negative integer n (n!), is the product of all positive integers less than or equal to n.

For example - Factorial of 5 is   5! = 5 * 4 * 3 * 2 * 1 = 120. It's very easy and you can easily calculate it.

But factorial of 100 has 158 digits. It's not possible to store it in long long int.

Find factorial of a number in java.

Find factorial of a number using recursion

Java programs

Java provides built-in data types such as int, float and long for handling numbers. These data types are not useful for very large numbers.

To tackle this problem, Java provides a custom class named BigInteger for handling very large integers (which is bigger than 64 bit values). The integer declared using this class has size equivalent to the available memory of the JVM.

Program to Find Factorial of Big Numbers


import java.io.*;
import java.util.*;
import java.math.*;

public class Solution {

    public static void main(String[] args) {
        
       BigInteger fact = BigInteger.ONE;
        
       Scanner in = new Scanner(System.in);
       int n = in.nextInt();
        
       for (int i = 1; i <= n; i++) {
            
         fact = fact.multiply(new BigInteger(String.valueOf(i)));
                
       }
        
       System.out.println(fact);
    }
}


No comments:

Post a Comment