You may face the problem of finding factorial of large numbers. Some people can use Long data type but that’s too not solve your problem.
So what could be the solution for it, one solution is the use of Java’s BigInteger class which provides operations analogues to all of Java’s primitive integer operators and for all relevant methods from java.lang.Math
.
Now I will show you how to use BigInteger class to find factorials of large numbers.
First you have to import the java.math.*;
to use the class BigInteger.
Here in the program we take the value from user and pass it as argument in the function fact().
Inside the fact(),
We declare two objects of BigInteger with initial values of 1.
In for loop we compare the two values ‘i and n’ using the compareTo()
method and increment the value of ‘i’ using method add()
of BigInteger class.
Multiplication is done using the multiply()
method and at last the computed value is returned back to the main function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.io.*; import java.math.BigInteger; class Factorial { public static void main(String args[] ) throws Exception { long n; System.out.print("\nEnter the value : "); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = br.readLine(); n = Long.parseLong(line); System.out.println("\nfact("+n+") : "+fact(BigInteger.valueOf(n))); } static BigInteger fact(BigInteger n) { BigInteger fat = BigInteger.valueOf(1); BigInteger i = BigInteger.valueOf(1); for ( ; (i.compareTo(n) == -1)||(i.compareTo(n) == 0); i=i.add(BigInteger.valueOf(1))) { fat = fat.multiply(i); } return fat; } } |