Java program to find factorial of a number

Write a java program to find factorial of a number

Here, we will used for loop to loop through all numbers between 1 and the given number num (10), and the product of each number till num is stored in a variable factorial.

We will used long instead of int to store large results of factorial. However, it's still not big enough to store the value of bigger numbers (say 100).

For results that cannot be stored in a long variable, we use BigInteger variable in java.math library.

  • Program:

import java.math.BigInteger;

public class Factorial {

    public static void main(String[] args) {

        int num = 11;
        BigInteger factorial = BigInteger.ONE;
        for(int i = 1; i <= num; ++i)
        {
            // factorial = factorial * i;
            factorial = factorial.multiply(BigInteger.valueOf(i));
        }
        System.out.printf("Factorial of %d = %d", num, factorial);
    }
}

Output:

Factorial of 11 = 39916800

  • Visit:

Java program to print an Integer Here
Java program to add two integers Here
Java program to find ASCII value of a character Here
Java program to compute quotient and remainder Here
Java program to swap two numbers Here
Java program to check whether a given number is even or odd Here
Java program to check whether an alphabet is vowel or consonant Here 
Java program to find the largest among three numbers Here
Java program to find all roots of a quadratic equation Here
Java program to check leap year Here
Write a java program to multiply two floating point numbers Here
Java program to check whether a number is positive or negative Here
Java program to check whether a character is alphabet or not Here
Java program to calculate the sum of natural numbers Here

0 comments