Hey folks, today in this blog you’ll see Factorial Program in Java. I have created blogs on making a Group Chat APP Using JAVA and in this fantastic blog, you will learn how to create a Factorial Program in Java. So, Factorial Program in Java: Factorial of n is the product of all positive descending integers. Factorial of n is denoted by n!.For example:
6! = 720 7! = 5040
Here, 6! is pronounced as “6 factorial”, it is also called “6 bang” or “6 shrieks”.
The factorial is normally used in Combinations and Permutations (mathematics).
The factorial of a positive number n is given by:
factorial of n (n!) = 1 * 2 * 3 * 4 * ... * n
There are many ways to write the factorial program in java language. Let’s see the 3 ways to write the factorial program in java.
You might like this:
- JavaScript Projects For Beginners
- Automatic Image Slider
- Sidebar Menu using HTML and CSS
- Cool Glowing Effect on Buttons
Example 1: Find the Factorial of a number using BigInteger
import java.math.BigInteger; public class Factorial { public static void main(String[] args) { int num = 30; 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 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 cast to BigInteger not long for multiplication.
Example 2: Find the Factorial of a number using the while loop
public class Factorial { public static void main(String[] args) { int num = 5, i = 1; long factorial = 1; while(i <= num) { factorial *= i; i++; } System.out.printf("Factorial of %d = %d", num, factorial); } }
Output
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 iterations (up to num) is known.
Example 3: Find the Factorial of a number using for loop
public class Factorial { public static void main(String[] args) { int num = 5; long factorial = 1; for(int i = 1; i <= num; ++i) { // factorial = factorial * i; factorial *= i; } System.out.printf("Factorial of %d = %d", num, factorial); } }
Output
Factorial of 5 = 120
In this program, we’ve used for loop to loop through all numbers between 1 and the given number num (5), 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 because it has less storage capacity compared to BigInteger, we use the BigInteger variable declared in java.math library.