Extra long factorials

Problem Statement

You are given an integer N. Print the factorial of this number.

N!=N×(N1)×(N2)××3×2×1

Note: Factorials of N>20 can’t be stored even in a 64bit long long variable. Big integers must be used for such calculations. Languages like Java, Python, Ruby etc. can handle big integers but we need to write additional code in C/C++ to handle such large values.

We recommend solving this challenge using BigIntegers.

Input Format
Input consists of a single integer N.

Constraints
1N100

Output Format
Output the factorial of N.

Sample Input

25

Sample Output

15511210043330985984000000

Solution

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

public class Solution {

    public static void main(String[] args)  throws Exception{
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        //BufferedReader br = new BufferedReader( new InputStreamReader(System.in));
        //int n = Integer.parseInt(br.read());
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        BigInteger ans = BigInteger.ONE;
        for (int i=1;i<=n;i++)
            {
            ans = ans.multiply(new BigInteger(String.valueOf(i))); 
        }
        System.out.println(ans);
    }
}

Leave a Reply