In this article, we will learn to write factorial code in Java. With Java being one of the most popular programming languages worldwide, we will be solving some of the most frequent problems using the Java programming language.
Factorial problem is a famous beginner problem frequently asked during technical or coding interviews. In mathematics, factorial is used in many places such as algebra, permutation, combination, power series, probability, and more. Let us learn to write factorial code in Java using Loops and Recursion methods but let us first know “what factorial actually is.”
What is Factorial?
Factorial is the repeated multiplication of a number by each number below it until it reaches the last number, i,e. 1. Factorials of a number N are the product of all positive numbers below the number till it reaches 1. It is represented by N! For instance,
Example of Factorial |
6! = 6x5x4x3x2x1 = 720
5! = 5x4x3x2x1 = 120 |
In the above example, we can see that we find factorial by repeated multiplication of a number from all numbers below it till the number reaches 1. The final multiplication answers. “6!” is pronounced as “6 Factorial”.
There are many methods we can write factorial code in Java. Let us know about factorial in this article.
How to Write Factorial Code in Java?
We can easily write factorial code in Java. Let us understand how to approach the solution to the given problem.
- Understand the logic of the problem: In the given situation, we know the formula for calculating the factorial of numbers. We will find our solution using formulas.
- Use For or While Loop: You can use either the “for” loop or a “while” loop to carry out repetitive multiplication and find factorials of a given number.
- Use Recursion: We can also use recursion to find factorials using Java.
Factorials are repeated multiplications of numbers in descending order. We will take this hint and start our solution. Let us understand both of these methods in detail below.
Problem Statement for Factorial Program in Java
Let us take an example of the problem statement you might get while facing the factorial problem.
Given a positive integer, N. Find the factorial of N.
Example 1: Input: N = 5 Output: 120 Example 2: Input: N = 6 Output: 720 |
Along with the above problem statement, you will get constraints, time complexity, and parameters. Here, we are considering both methods to calculate factorial hence, we are not considering the additional constraints.
Factorial Code in Java using For Loop
Let us use a for loop to calculate factorials of a given number in Java.
Factorial code in Java using For Loop |
public class Factorial {
public static void main(String[] args) { int number = 6; // given number is 6, we have to find factorial. long factorial = 1; for (int i = 1; i <= number; i++) { factorial *= i; } System.out.println(“Factorial of given number ” + number + ” = ” + factorial); } } |
Output
Factorial of given number 5 = 120 |
Explanation
- First, we will take a number inside the main function for which we want to calculate the factorial.
- Now, run a for loop until the given number.
- Keep on multiplying factorials with the index of the for loop till it becomes equal to or greater than the number itself.
- Return the factorial
The time complexity of the given solution is O(N), which becomes too lengthy when the number is large and hence is not considered an optimal solution for the given factorial program in Java.
Factorial Code in Java using While Loop
Let us now use the while loop to find the factorial of a number in Java below.
Factorial code in Java using While Loop |
import java.util.Scanner;
public class FactorialWhileLoop { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print(“Enter a number: “); int number = scanner.nextInt(); long factorial = 1; // Using long to handle large factorials int i = 1; while (i <= number) { factorial *= i; i++; } System.out.println(“Factorial of ” + number + ” = ” + factorial); } } |
Output
Enter a number:
6 Factorial of 6 = 720 |
Explanation
- Import scanner class, we will use it to scan input given by our users.
- First, declare and initialize a new variable.
- Now declare a new variable for the loop and store the factorial of a number in it.
- Initialize both variables with 1.
- Now, for traversal, we will use a while loop till the given number.
- We will keep updating the factorial in each iteration
- Increment the loop variable i,e i
- Finally, print the factorial of a number for the users.
Factorial Code in Java using Recursion
Let us now use another method i,e recursion to find the factorial of a given number using Java.
Factorial code in Java using Recursion |
import java.util.Scanner;
public class FactorialRecursion { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print(“Enter a number: “); int number = scanner.nextInt(); long factorial = factorial(number); System.out.println(“Factorial of ” + number + ” = ” + factorial); } public static long factorial(int n) { if (n == 0) { return 1; // Base case for the given function } else { return n * factorial(n – 1); // Recursive calling } } } |
Output
Enter a number:
6 Factorial of 6 = 720 |
Explanation
- We will first import the scanner class, which can read the input given by the user.
- Declare a variable to store the factorial of the number.
- Ask the user to enter the number.
- Create a separate function, i,e factorial ()
- Take the number as a parameter.
- Create a base condition i,e when the n value goes to 0, we will return 1.
- Keep calling the function recursively.
Learn Programming in Java with PW Skills
Enroll in our Decode DSA With Java Program and start learning Java along with Data structure and algorithms. Get in-depth learning with our self-paced course and industry-level experts throughout the course.
Practice real-world problems while attending tutorials and working on various projects to strengthen your knowledge and become a proficient developer only at pwskills.com
Factorial Code in Java FAQs
Q1. How do I find the factorial of a number using a loop?
Ans: Follow the steps below to find the factorial of a number below.
1. Initialize a variable with n, which is the number we have to find factorial. It is a fixed value, say n is 6.
2. Now, another variable, factorial, initializes factorial to 1.
3. During each iteration, store the answer of the previous and keep on incrementing the number.
Q2. Which is a better method to find factorials: Recursion or Iteration?
Ans: You can use the recursion method to find the factorial of a number but it takes a lot of extra space and is costly. Hence, an iterative method to find factorials is better than recursion. You can find factorials in constant space using recursion which makes it more cost effective.
Q3. What is the complexity of factorials using recursion?
Ans: The time complexity of factorials using recursion is O(N), where N = given number.