Java Code to find out factorial of any Number

Write a Java Code to find factorial of any Number?  is most important coding question for freshers. We can find out the factorial of any number by using simple method and also by recursion method.

We can use Scanner class as well to take input from the user and based of that input we can find the factorial of that number.

By using simple method

				
					import java.math.BigInteger;

public class Test {

    static int fact = 1;
    public static void main(String[] args) {
        int inputNumber = 25;
        BigInteger result = findFactorail(inputNumber);
        System.out.println("Factorial of " + inputNumber + " is : "+result);
    }

    private static BigInteger findFactorail(int n){
        BigInteger fact = BigInteger.ONE;
        for(int i=1; i<=n; i++){
            fact = fact.multiply(BigInteger.valueOf(i));
        }
        return fact;
    }
}

				
			

Output:

				
					Factorial of 25 is : 15511210043330985984000000
				
			

In the above code we are taking BigInteger instead of int, It is because the range of int in java is from -2147483648 to 2147483647.
And hence we can not store the value greater than 2147483647. Thats why we have taken BigInteger. Becuase it can store larger value.

By using Recursion method

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

public class FactorialByRecursion{

    static BigInteger fact = BigInteger.ONE;
    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        System.out.print("Enter any no to find factorial : ");
        int number = scan.nextInt();
        factorial(number);
        System.out.println(fact);

    }

    public static void factorial(int number){
        if(number>=1){
            fact = fact.multiply(BigInteger.valueOf(number));
            factorial(number - 1);
        }
    }
}
				
			

Output:

				
					Enter any no to find factorial : 26
Factorial of 26 is : 403291461126605635584000000
				
			

So, by using both above methods you can find out the factorial of any number. 

If you have any question then you can contact us and send the question, we will help you out as soon as possible.

Scroll to Top