Java Program to find Factorial of a Number using BigInteger - The Coding Shala

Home >> Java Programs >> Factorial Program using BigInteger

 In this post, we will learn how to find Factorial of a Number using BigInteger in Java.

Java Program to find Factorial of a Number using BigInteger

We use int or long to store the result of factorial but long is also not enough to store the value of factorial of larger numbers, let's say n = 100 so in Java, we use BigInteger to store the factorial of large numbers.

Example 1:
Input: 30
Output: 265252859812191058636308480000000

Java Program: 

// Java program to Find Factorial using BigInteger

import java.util.Scanner;
import java.math.BigInteger;

public class Main {
	
	public static void main(String[] args) { 
		Scanner sc = new Scanner(System.in);
		
		// take number input
		System.out.println("Enter the number");
		BigInteger num = sc.nextBigInteger();
		
		BigInteger fact = BigInteger.ONE;
		BigInteger i = BigInteger.ONE;
		
		// calculate factorial
		while(i.compareTo(num) <= 0) {
			fact = fact.multiply(i);
			i = i.add(BigInteger.ONE);
		}
		
		System.out.println("Factorial of " + num + " is: " + fact);
		
		sc.close();
	}
}

Output: 

Enter the number
30
Factorial of 30 is: 265252859812191058636308480000000

Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Java Program to Convert Binary to Decimal - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Introduction to Kotlin Programming Language for Backend Development - The Coding Shala

Java Program to Reverse a String using Stack - The Coding Shala