Java Program to Find Factorial of a Number

In this program, you’ll learn to find the factorial of a number using for and while loop in Java.

The factorial of a positive number n is given by:

factorial of n (n!) = 1 * 2 * 3 * 4 * ... * n

Example 1: Find Factorial of a number using for loop

  1. public class Factorial {
  2. public static void main(String[] args) {
  3. int num = 10;
  4. long factorial = 1;
  5. for(int i = 1; i <= num; ++i)
  6. {
  7. // factorial = factorial * i;
  8. factorial *= i;
  9. }
  10. System.out.printf("Factorial of %d = %d", num, factorial);
  11. }
  12. }

When you run the program, the output will be:

Factorial of 10 = 3628800

In this program, we’ve 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’ve 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 declared in java.math library.

Example 2: Find Factorial of a number using BigInteger

  1. import java.math.BigInteger;
  2. public class Factorial {
  3. public static void main(String[] args) {
  4. int num = 30;
  5. BigInteger factorial = BigInteger.ONE;
  6. for(int i = 1; i <= num; ++i)
  7. {
  8. // factorial = factorial * i;
  9. factorial = factorial.multiply(BigInteger.valueOf(i));
  10. }
  11. System.out.printf("Factorial of %d = %d", num, factorial);
  12. }
  13. }

When you run the program, the output will be:

Factorial of 30 = 265252859812191058636308480000000

Here, instead of long, we use BigInteger variable factorial.

Since, * cannot be used with BigInteger, we instead use multiply() for the product. Also, num should be casted to BigInteger for multiplication.


Likewise, we can also use a while loop to solve this problem.

Example 3: Find Factorial of a number using while loop

  1. public class Factorial {
  2. public static void main(String[] args) {
  3. int num = 5, i = 1;
  4. long factorial = 1;
  5. while(i <= num)
  6. {
  7. factorial *= i;
  8. i++;
  9. }
  10. System.out.printf("Factorial of %d = %d", num, factorial);
  11. }
  12. }

When you run the program, the output will be:

Factorial of 5 = 120

In the above program, unlike a for loop, we have to increment the value of i inside the body of the loop.

Though both programs are technically correct, it is better to use for loop in this case. It’s because the number of iteration (upto num) is known.

Visit this page to learn to find factorial of a number using recursion.