Have you ever thought about how to calculate the factorial of a number in Java? What exactly is a factorial, and where is it used in real life or programming? Can we solve it using loops, recursion, or modern Java features like Streams? What is the most efficient way to handle large factorials in Java?
In this article, we will learn about how to find the Factorial of a number in Java in detail.
Table of Contents:
What is Factorial in Java?
The factorial of a number in Java is the product of all the positive integers that are less than or equal to that number. In factorial, we keep multiplying that number by every whole number smaller than it, down to 1. It is represented by an exclamation mark (!).
Let us now take an example of a Factorial Program in Java. The factorial of 5 is written as 5! and it represents the product of all positive integers from 1 to 5, which is discussed below
5! = 5 × 4 × 3 × 2 × 1 = 120
The factorial values for small numbers, like
- 0! = 1 (by definition)
- 1! = 1
- 2! = 2 × 1 = 2
Master Java Today - Accelerate Your Future
Enroll Now and Transform Your Future
Factorial Program in Java using a For-Loop
The for-loop in Java is the simplest way to calculate the factorial of a number, it multiplies the numbers from 1 up to the given number n to find the factorial of n. This method is very efficient for small inputs and easy to understand for beginners.
Example:
Output:
Explanation:
In the above Java program, the for-loop is used to iterate from 1 to n, where n is the number for which the factorial has to be calculated. Each time, the current value of i is multiplied by the existing value of factorial, and the result is stored back in factorial.
Factorial program in Java using a While Loop
The while loop is another iterative method to find the factorial of a number, and it works the same as the for loop as discussed above, but the initialization and increment are handled separately. This method is useful when the number of iterations is not fixed or has to be controlled manually.
Example:
Output:
Explanation:
In the above Java program, the while loop is used to find the factorial of the number. The while loop runs from the value 1 to the condition i <= number, every time the factorial variable is multiplied by i.
Factorial Program in Java using Recursion
Recursion is a technique in which a method calls itself to solve smaller sub-problems of a bigger problem. It is a common way to solve when the tasks are repeated in a pattern like factorial.
For recursion, the factorial can be defined as,
n! = n × (n - 1)!
Now, let the function factorial(int n) be the function, where n is the number. Then the base condition of this will be,
If n == 0, return 1
Example:
Output:
Explanation:
In the above Java program, the technique of recursion is used to find the factorial of a number.
The function factorial(int n) is used, which takes an integer as a parameter and returns the factorial of the number, having the base condition if (n == 0).
Get 100% Hike!
Master Most in Demand Skills Now!
Factorial Program in Java using Scanner
In Java, the Scanner class is used to take user input from the console, and is helpful when you want the user to enter a number at runtime. The Scanner class allows reading input from the keyboard, and it is present in java.util package.
Example:
Output:
Explanation:
In the above Java program, the input is taken from the user, and then the for-loop method is used, as given above, to find the factorial of a number.
Factorial Program in Java using the Ternary Operator
The ternary operator in Java is a concise way to write conditional logic and is often referred to as the conditional operator, which is best suited for simple if-else conditions.
Syntax:
condition ? result_if_true : result_if_false;
It evaluates the condition and based on that it returns:
- result_if_true, if the condition is true,
- result_if_false, if the condition is false,
Example:
Output:
Explanation:
In the above Java program, the ternary operator is used to find the factorial of the number, which serves as a shorthand for the if-else statement. Further, the main idea of the recursion is used with the ternary operator to make the code concise.
Factorial Program in Java using BigInteger
BigInteger is an immutable class that provides operations for arbitrary-precision integers. It supports arithmetic operations, comparisons, modular arithmetic, bit manipulation, and more, and works similarly to an integer, but without the size limitations.
Example:
Output:
Explanation:
In the above Java program, the for-loop and BigInteger are used to find the factorial of a given number, 25. BigInteger is used to handle very large numbers without overflow, which provides arbitrary-precision arithmetic.
Factorial Using Java 8 Streams
Java 8 has a feature called the Stream API, which lets you work with collections or ranges of numbers in a clean and functional way. To find the factorial of a number, we can use IntStream, which creates a range of numbers from 1 to n. Then, we use the reduce() method to multiply all those numbers together, which will give us the factorial. This method is short, clear, and uses modern Java coding style. It is a smart way to write factorial logic without using loops or recursion.
Example:
Output:
Explanation:
In the above Java program, the Stream API of Java 8 is used to find the factorial of the number. The IntStream.rangeClosed(1, number) generates numbers from 1 to number, and then reduce(1, (a, b) -> a * b) multiplies all the numbers together, starting with an initial value of 1.
Note: Streams use internal iteration
Factorial Java Program Using Memoization Approach
Memoization is a technique that stores the previous results to avoid unnecessary calculations and improve the performance of the calculation of a recursive factorial program by caching the results of subproblems.
Example:
Output:
Explanation:
In the above Java program, a HashMap is used to store the values that have already been computed. The recursive function first checks the HashMap to see if the result is in the cache or not. If it is not present, then it calculates the factorial, stores it, and returns it, which avoids repeated calculations and makes recursion efficient.
Program to Count Trailing Zeros Using Factorial in Java
Trailing zeros are the zeros at the end of a number. For example: 5! = 120, it has 1 trailing zero.
These zeros come when a number is multiplied by 10 (2 × 5). Every time we multiply a number by 2 and 5, we get a trailing zero. But in any factorial, we get more 2s than 5s. In this case, the number of trailing zeros depends on how many 5s are there in the multiplication.
Example:
Output:
Explanation:
The above Java program counts how many multiples of 5, 25, 125, etc., divide n, and each one of them contributes at least one factor of 5, which pairs with a 2 to form a zero. The expression count += n / i adds the number of multiples that are present at each power of 5, and this gives the total number of trailing zeros in n!.
Time and Space Complexity of Different Factorial Methods
Method |
Time Complexity |
Space Complexity |
For Loop |
O(n) |
O(1) |
While Loop |
O(n) |
O(1) |
Recursion |
O(n) |
O(n) |
Ternary Operator |
O(n) |
O(n) |
Memoization |
O(n) |
O(n) |
BigInteger |
O(n) |
O(1) |
Java 8 Streams |
O(n) |
O(n) |
Real World Applications of Factorial Program in Java
- Factorials are used in formulas of combinations and permutations to calculate arrangements or selections, in lottery systems, games, and scheduling tasks.
- Factorials are important in solving the problems of probability, where outcomes and arrangements of events are involved, such as card games, dice rolls, or statistical calculations.
- Some algorithms rely on factorial logic, especially in optimization and problem-solving contests like backtracking.
- Factorials are used in Bezier curve calculations and in certain physics simulations where mathematical modeling involves combinations and permutations.
Unlock Your Future in Java
Start Your Java Journey for Free Today
Conclusion
From the above article, we conclude that factorial programs in Java are a great way to understand the concept of programming concepts. You can write them in many ways, using loops, recursion, BigInteger, or even Java 8 Streams. Factorials are not only used in the programming world, they have many real-life applications, like in maths, probability, and counting arrangements. By learning this concept, you can improve your Java skills step by step.
If you want to learn more about this topic, you can refer to our Java course.
Factorial Program in Java – FAQs
Q1. What is factorial in Java?
The factorial in Java is the product of all positive numbers from 1 to n.
Q2. What is the factorial of 1?
Q3. Why is zero factorial 1?
Zero factorial is 1 by definition in math to make formulas work correctly.
Q4. How to define a constructor in Java?
A constructor is defined using the class name without a return type, and it runs when an object is created.
Q5. How to solve 3 factorial?
The factorial of 3 = 3 × 2 × 1 = 6.