Pages

Extra Long Factorials

Extra Long Factorials
Write a program that will accept an integer. Find the factorial of that number
Note: Note that for N>20 you can't use 64-bit variables as they won't be able to store such a large data.
Input
An Integer number N, where 0 < N < 1000
input : 25
Output
Display the factorial of that number N
output : 15511210043330985984000000
Finding the factorial of a number is not a big task, you just have to loop through 1 to maximum limit and keep multiplying each value to it's previous value. Here is the code for it.
import java.util.Scanner;
class FactorialExample{ public static void main(String args[]){
int i,fact = 1; Scanner sc = new Scanner(System.in); int number = sc.nextInt();  //It is the number to calculate factorial   for(i=1; i<=number; i++){ fact=fact*i; } System.out.println("Factorial of "+number+" is: "+fact); } }
But the problem with above program is that it will work only for small values. So, if you want to find factorial of large numbers then java.math.BigInteger class is useful for that. Java provides a custom class named BigInteger for handling very large integers (which is bigger than 64 bit values). This class can handle very large integers and the size of the integer is only limited by the available memory of the JVM.
import java.util.*;
import java.math.*;
public class Solution {
    public static void main(String[] args) {         Scanner in = new Scanner(System.in);         int n = in.nextInt();        
        BigInteger result = BigInteger.ONE;         for(int i=2; i<=n; i++){             result = result.multiply(BigInteger.valueOf(i));         }         System.out.println(result);     } }

No comments:

Post a Comment