Find Factorial of Extra Long Number | Factorial of BigInteger in Java | HackerRank Problem
Problem Description :
Calculate and print the factorial of a given integer.
The factorial of the integer n, written n!, is defined as:
n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1
Example 1 :
n = 30
ans = 265252859812191058636308480000000
Explanation = 30 * 29 * 28 * 27 * .... * 3 * 2 *1
Example 2 :
n = 50
ans = 30414093201713378043612608166064768844377641568960512000000000000
We can not store large number in Long data type as well. So we need BigInteger for that.
BigInteger class presents in java.math package. For use BigInteger we need to import math package first.
Checkout How we can divide and compute modulo of BigInteger in Java :
Lets solve long number factorial problem.
Solution 1 : Factorial of Extra long number in Java
import java.util.Scanner;
public class ExtraLongFactorials {
BigInteger factorial = BigInteger.ONE;
Output :
n = 30
265252859812191058636308480000000
n = 50
30414093201713378043612608166064768844377641568960512000000000000
We can see that how large factorial of 30 and 50 is, clearly it is not possible to use long data type to store huge integer values. We need BigInteger Class to store such large numbers.
Lets see another solution with while loop.
Solution 2 : Find Factorial of BigInteger in Java
import java.math.BigInteger;
RECOMMENDED ARTICLES :
- Bill Division HackerRank Solution in Java and Python with Explanation
- Drawing Book HackerRank Solution in Java and Python with Explanation
Comments
Post a Comment