Fill your College Details

Summarise With AI
ChatGPT
Perplexity
Claude
Gemini
Grok
ChatGPT
Perplexity
Claude
Gemini
Grok
Back

Factorial Program in Java: A Complete Guide

12 Sep 2025
5 min read

The Factorial Program in Java is a foundational practice for understanding mathematical operations and programming constructs. Factorial numbers, denoted by n!, are the product of all the positive integers from 1 - n. This concept is important not only in mathematics but also in various real-world applications, making it a common topic in programming tutorials.

🎯 Calculate your GPA instantly — No formulas needed!!

Factorial Of a Number

The factorial of a non-negative integer n is the product of all positive integers from 1 up to n. It is written as n!. In simple terms, to find the factorial of a number, you multiply it by every smaller whole number down to 1.

Mathematical Definition

The factorial of n can be represented as:

n! = n×(n−1)×(n−2)×…×1

For example:

  • 3!=3×2×1=6
  • 5!=5×4×3×2×1=120

The factorial of 0, denoted as 0!, is defined as equal to 1 by convention to confirm mathematical consistency in equations involving permutations and combinations. The  Factorial of a negative number is not defined. The factorial function has applications in fields such as mathematics, statistics, and computer science. This article examines different ways of implementing the factorial function in Java, including iteration methods (by loops), recursion and manipulation with a large number with the BigInteger class.

Factorial Calculation Methods in Java

It is important to understand that the implementation may vary depending on the requirements of the problem, the input size and the need for optimization. Factorial in Java encourages developers to manage efficiency, readability, and scalability.

For example, recurrent methods are straight and sharp to small numbers, while recurrence provides purification but risks stack overflow for large inputs. Similarly, advanced techniques are required to handle large numbers, such as using Java's BigInteger class. By searching various approaches, developers can choose the most suitable method for their specific use case.

1. Factorial Code in Java Using Iteration

Let us start by discovering a recurring approach that is the easiest and most commonly used methods for calculating factors in Java.

a. Factorial program using for loop in Java

Example:

import java.util.Scanner;

public class FactorialWithForLoop {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int number = input.nextInt();

        int factorial = 1;
        for (int i = number; i > 0; i--) {
            factorial *= i;
        }

        System.out.println("Factorial of " + number + " is: " + factorial);
    }
}

Input:

Enter a number: 5

Output:

Factorial of 5 is: 120

Explanation of the Code:

The product of every single positive integer to a specified number, denoted as n!, is known as a factorial. The application starts by asking the user to utilise the scanner class to enter a number.

It then integrates a variable factorial for 1 and uses a for loop to make the factorial down to 1 by each number from the input value. 

Complexity of the code:

Time Complexity: The for loop runs from the given number n down to 1, performing a single operation (multiplication) in each iteration. Therefore, the number of iterations is proportional to n. The time complexity is O(n)

Space Complexity: The program only uses a continuous amount of additional space, regardless of input shape, and O(1) is the space complexity.

b. Java Factorial program using a Do-While Loop

import java.util.Scanner;

public class FactorialWithDoWhileLoop {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int number = input.nextInt();

        int factorial = 1;
        int i = number;
        do {
            factorial *= i;
            i--;
        } while (i > 0);
        System.out.println("Factorial of " + number + " is: " + factorial);
    }
}

Input:

Enter a number: 4

Output:

Factorial of 4 is: 24

Explanation of the Code:

This code does a factorial of the number supplied by the user. After prompting the user for input, it initializes the factorial variable to 1, and the variable i to the user input.

The Do-While Loop is used, so that the loop body will perform the task at least once. This is wanted, because if user inputs 0 or negative numbers, it still enters 1 when calculating factorials of 0 and negative numbers. Then the multiplying factor multiplied is multiplied by i and decreased by 1 each time. When i becomes 0 then the loop exits.

Complexity of this code:

Time Complexity:

‍The do-while loop runs from the given number n down to 1, performing a single multiplication and decrement operation in each iteration. The number of iterations is proportional to n. The time complexity is O(n).

Space Complexity:

‍The program uses only a constant amount of extra space, regardless of the input size.The space complexity is O(1).

Why is it better to use for loop in this case?

Using a for loop is preferred over a do-while loop in cases like this because it provides a more intuitive and compact structure for iterating through a fixed range of numbers. The loop starts with the input number in a factual calculation, drops to 1, permits the original point, stops the position, and the updated action is explicitly specified in the loop header.

2. Factorial Using Recursion

Factorial recursion is a technique in which a function solves for a number of factorials through self-referent calls, progressively solving the problem until it can work back through the stack to aggregate the results for the total solution. The problem is simplified to the minimum base case, which is small and simple to solve.

Base Case:

The base case is the condition that defined how or when the program will stop recursing to prevent infinite recursion. For instance, the factorial of 0 or 1 is 1, so these base cases are designated for a factorial function. A factorial recursion without the base case (0 or 1 would be the base case values) would continue infinitely, causing an eventual stack overflow error. The following is an example of a recursive factorial:

  • 5!=5×4!
  • 4!=4×3! and this resolves;
  • 1! = 1 (base case) reaches to avoid recurrence and begins to return the values down the call stack..

Algorithm

  1. Start.
  2. Read input number (n) from the user.
  3. If n < 0:
    1. Display an error message and stop.
  4. If n is 0 or 1:
    1. Return 1.
  5. Otherwise:
    1. Return the ‘n’ multiplied by the result of calling the same function with (n-1).
  6. Stop.

Algorithm Explanation for Recursive Factorial Calculation

  1. In the base case, return 1 if n == 0 or n == 1.
  2. Otherwise, return n * factorial(n -1)
  3. Thus, drop down the call stack until reaching the base case, then return to the previous call stack. 

Example Code:


import java.util.Scanner;
public class FactorialWithRecursion {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int number = input.nextInt();

        long result = findFactorial(number);
        System.out.println("Factorial of " + number + " is: " + result);
    }
    public static long findFactorial(int n) {
        if (n <= 1) {
            return 1;
        }
        return n * findFactorial(n - 1);
    }
}

Input:

Enter a number: 5

Output:

Factorial of 5 is: 120

The program describes how to use recursion to find the actual value of the number input by the user in this Java program. After entering a number, the main method invokes the recurrence method Findfactorial. The findfactorial method works by multiplying the current number n by the Factorial of n-1. The recursion ends when n becomes smaller than or equal to 1. In that case, it returns 1.

Complexity of the code:

Time Complexity: Each call to findFactorial makes one recursive call until n reaches 1. For an input number n, there are n recursive calls. The time complexity is O(n).

Space Complexity: The program uses space proportional to the depth of the recursion stack. The space complexity is O(n).

3. Factorial Java Program Using Ternary Operator

A factorial program using a ternary operator in Java calculates a number factorial by replacing a traditional If-Else statement with a compact ternary operator.

It uses a recurrent approach where the turnry operator checks whether the input ≤ 1 (base case) and gives 1 return, or calculates the factorial by multiplying the number by the factorial of the previous number.

Algorithm

  1. Start.
  2. Read input number (n) from the user.
  3. If n is less than or equal to 1, then return 1.
  4. Otherwise, use a ternary operator for conditional logic to return n multiplied using a factorial of (n-1).
  5. Stop.

Algorithm Explanation for Factorial Java Program Using Ternary Operator

  1. Define a recursive function for finding a factorial..
  2. In the function, use a ternary operator to test if the input n is less than or equal to 1 (the base case). 
    • If true, return 1.
    • If false, return n multiplied by Factorial of (n-1) (recursive case).
  3. The ternary operator is a optimized way to express if/else logic in single line of code.

Example Code:


import java.util.Scanner;

public class FactorialWithTernaryOperator {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int number = input.nextInt();

        long factorial = findFactorial(number);
        System.out.println("Factorial of " + number + " is: " + factorial);
    }

    public static long findFactorial(int n) {
        return (n <= 1) ? 1 : n * findFactorial(n - 1);
    }
}

Input:

Enter a number: 4

Output:

Factorial of 4 is: 24

Explanation of the Code:

This program computes the factorial of a number using the ternary operator in a recursive function. The ternary operator is simply a shorthand for implementing an if-else condition. After the user inputs a number, the main method invokes the recursive function findFactorial, which computes the factorial.

The function checks if n≤1 using the condition (n \<= 1). If true, it returns 1 (base case). Otherwise, it returns n×findFactorial(n−1).

Complexity:

Time Complexity: For each recursive call, you are doing one multiplication by n and repeating until n = 1 means there are n recursive calls for an input number n, therefore the time complexity is O (n)

Space Complexity: The amount of space used by the program is equivalent to the depth of the repeated stack. The depth of the recurrence is n. Therefore the space complexity is O (n).

4. Factorial Java Program Using Memoization Approach

By storing the pre-calculated results in a HashMap, a Java Factorial Program that employs memoization technology optimizes Factorial Computation. This makes the program more efficient for large inputs by avoiding redundant calculations in recurrence. If a factorial is already calculated by an integer, it is obtained directly from the map instead of recomputation.

Algorithm

  1. Start.
  2. Read input number (n) from the user.
  3. Create a map or array to store computed factorials.
  4. If n is less than or equal to 1, return 1.
  5. If the factorial of n is already stored, retrieve and return it.
  6. Otherwise, compute the factorial recursively as n multiplied by the factorial of (n-1).
  7. Store the computed result for n in the map or array.
  8. Return the result.
  9. Stop.

Algorithm Explanation for Memoization Approach

  1. Use a map or dictionary to keep record of previous factorials.
  2. If n is 0 or 1, then return 1.
  3. If you have the factorial of n in the map, return it.
  4. Otherwise calculate factorial(n-1) by recursive call, multiply it by n, keep in map, then return value.

Example


import java.util.HashMap;
import java.util.Scanner;

public class FactorialWithMemoization {
    private static HashMap<Integer, Long> memo = new HashMap<>();

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int number = input.nextInt();

        long factorial = findFactorial(number);
        System.out.println("Factorial of " + number + " is: " + factorial);
    }

    public static long findFactorial(int n) {
        if (n <= 1) {
            return 1; // Base case
        }

        // Check if the factorial of n is already computed
        if (memo.containsKey(n)) {
            return memo.get(n);
        }

        // Compute and store the result in the HashMap
        long result = n * findFactorial(n - 1);
        memo.put(n, result);
        return result;
    }
}

Input:

Enter a number: 5

Output:

Factorial of 5 is: 120

Explanation of the Code:

This program calculates a factorial for a number using memoization, a process of executing recursion more efficiently by remembering previous calls. The program has a HashMap, which is named memo, to store factorial values for numbers for which it has already computed the factorial.

After the user enters a number, the main method calls the function, findFactorial. The findFactorial method checks if the factorial for n is already in the map.

Complexity of the code:

Time Complexity: Because every unique factorial is calculated just once and saved in a hash map, retrieval time is constant. Since each recursive call operates on a different number, the factorial calculation's temporal complexity is O(n).

Space Complexity: HashMap stores values from 1 to n, the space it uses to store factorials is O(n).

5. Handling Large Numbers with BigInteger

When calculating factorials for a large number, the BigInteger class in Java.math package can be used to prevent overflow.

Algorithm

  1. Start.
  2. Read input number (n) from the user.
  3. Initialize a variable fact as a BigInteger with value 1.
  4. For each integer i from 1 to n (inclusive):
    1. Multiply fact by i (converted to BigInteger).
    2. Store the result back in fact.
  5. After the loop ends, print fact as the factorial of n.
  6. Stop.

Algorithm Explanation for Handling Large Numbers with BigInteger

  1. Initialize a variable (factorial) as a BigInteger with value 1.
  2. Loop from 1 up to the input number n (inclusive).
    • In each iteration, multiply the factorial variable by the current loop index (converted to BigInteger).
    • Update the factorial variable with the new value.
  3. After the loop completes, the factorial variable contains the result as a BigInteger.
  4. Output the result.

Example


import java.util.Scanner;
import java.math.BigInteger;
import java.util.Scanner;

public class FactorialWithBigInteger {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int number = input.nextInt();

        BigInteger factorial = BigInteger.ONE;
        for (int i = 1; i <= number; i++) {
            factorial = factorial.multiply(BigInteger.valueOf(i));
        }

        System.out.println("Factorial of " + number + " is: " + factorial);
    }
}

This Java code calculates the factorial of a given number using a BigInteger to handle large numbers. 

Input:

Enter a number: 20

Output:

Factorial of 20 is: 2432902008176640000

Explanation of the Code:

The program calculates the factorial of a number using the BigInteger class, which allows the program to handle a large number that exceeds the limit of primitive data types such as int or long. The user is motivated to enter a number, and the program uses a for loop to calculate the factorial. In each recurrence, the current value of the factial is multiplied by the next integer (starting from 1 upto input number).

Complexity of the code:

Time Complexity: Calculating factorial requires nnn multiplications, so the time complexity is O(n).

Space Complexity: The result is stored in a BigInteger (or integer variable), which grows with the size of n!, so the space complexity is O(1) aside from the output storage.

Important Note: Primitive data types in Java, including int and long, have restrictions and are not enough to store enormous values, such as large integer factorials. Because factorials expand exponentially, this range occurs. Java offers the BigInteger class in the java.math library to manage such large-scale integers without causing overflow problems.

6. Factorial Using Streams (Java 8 and Above)

With Java 8, factorial calculation can be achieved using the IntStream class:

Algorithm 

  1. Start.
  2. Read input number (n) from the user.
  3. Create an integer stream ranging from 1 to n (inclusive).
  4. Use a reduction operation to multiply all numbers in the stream together, starting from 1.
  5. Store the result.
  6. Print the result as the factorial of n.
  7. Stop.

Algorithm Explanation for Streams Approach

  1. Generate a sequence of a number integers from 1 to n.
  2. Use a reduction operation to multiply all values in the sequence together.
  3. The result is the factorial of n.

Example

import java.util.Scanner;
import java.util.stream.IntStream;

public class FactorialWithStreams {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int number = input.nextInt();

        long factorial = IntStream.rangeClosed(1, number)
                                   .reduce(1, (a, b) -> a * b);

        System.out.println("Factorial of " + number + " is: " + factorial);
    }    
}

Input:

Enter a number: 6

Output:

Factorial of 6 is: 720

Explanation of the Code:

This program calculates the factorial of a number using Java Streams. The IntStream.rangeClosed(1, number) creates a stream of integers starting from 1 to the number entered by the user. The reduce(1, (a, b) -> a * b) operation is used to accumulate the result of multiplying all the numbers in the stream.

Complexity of the code:

Time Complexity: The stream processes numbers from 1 to nnn once, so the time complexity is O(n).

Space Complexity: No extra space is used apart from variables for calculation, so the space complexity is O(1).

Applications of Factorial Program in Java

Factorials play an important role in solving problems across various industries. Here’s how factorials are used in real-world scenarios.

custom img

1. Data Science and Machine Learning

Factorials are common and helpful in data science and machine learning; especially when you are working with statistical models and probability distributions. They are used in two ways:

a) Probability Calculations:

Factorials are used in calculating event likelihood. For example, binomial probability distributions use factorials in their formulas, which include calculating combinations:

P(X=k) = (kn​)pk(1−p)n−k

b) Permutations and Combinations:

Factorials are extremely useful to calculate the number of ways the data can be arranged or grouped. In examples such as feature selection, better understanding of permutation will lead to improved model-building.

c) Markov Chains and Transition Models:

Factorials are used in higher-order models where sequences of states need to be computed, and factorials help in understanding the total number of permutations for states.

2. Graphics and Game Development

In entertainment and gaming, factorials can help with combinatorial logic to implement levels, animations and game mechanics:

a) Permutations of Objects:

When developing interactive items like puzzles or character arrangements you can use factorials to calculate all the possible layouts. As an example, if you had 5 game characters, you can see the total arrangement of those characters in a lineup can be calculated with the following equation for factorial, which is stated with n! (n factorial):
5!=5×4×3×2×1=120

b) Animation and Keyframe Interpolation:

Factorials are useful in rendering smooth transitions between keyframes. With techniques such as Bezier curves which are computed from combinatorial mathematics, you are able to calculate on the basis of a factorial.

c) Procedural Generation:

Games like the Minecraft or No Man's Sky build the worlds on a larger scale and are directed by code. The employment of factorials can be used to create random arrangements of objects, as long as they have limitations on what is allowed to happen.

d) Combinatorial Logic in Gameplay:

Factorials can assist in balancing challenges in the game mechanics. The factorials can be calculated upon how many combinations it will take a player to be successful in solving a puzzle. By being able to understand this part of the design, the designer will be able to determine that the challenge of play will be balanced out for players across the puzzle roster.

3. Optimization Algorithms

Optimisation is a recognition, and it is prominent in many fields such as logistics, manufacturing, and IT. Factorial can be applied as a resource for brute-force (or recursive) ways to help find an optimal solution for those complex problems:

a) Scheduling Problems:

Within manufacturing, healthcare, and aviation the factorial is used to consider every possible schedule of resources.

b) Traveling Salesman Problem (TSP):

TSP is a classic optimisation problem the factorial plays an important role. If a salesman must visit n cities, there are then n! possible routes. While one can hardly calculate each permutation for large n, factorials can still help understand the scale of the problem and perhaps help develop approximation algorithms.

c) Resource Allocation:

In IT Infrastructure, deciding how to set-up servers, storage, or bandwidth can actually rely on factorials. Think of your scenario where you have n data centres, and because of your business case you would need an mm configuration. This quickly leads to an explosion of combinations. Factorials help quantify the number of options to consider.

d) AI Pathfinding:

Factorials also play a role in robots and AI; in particular when it comes to traversing via decision making of state combinations, which heavily relies on paths.

Factorial calculations are the basis of all of these complex problems to solve. Factorial calculations of a value, while simple for small values, will typically require algorithms and data structures to be successfully applied for industrial usage with large values of factorials.

Conclusion

Factorial calculations are a basic concept in mathematics and programming, which contain extensive applications in areas such as data science, game development and adaptation. Factorials in Java can be calculated using various methods, including recurring loops, recurrences and renewers to handle large values.

Frequently Asked Questions

1. What is a factorial?

A factorial of a number is the result of multiplying all positive whole numbers from 1 up to that number.

For instance,

5! = 5 × 4 × 3 × 2 × 1 = 120.

2. How does recursion work in calculating factorials?

A function that uses recursion calls itself with fewer arguments. It multiplies the result until it reaches the base case, which is usually 1. The recursion ends once it reaches that base case.

3. How to calculate large factorials in C?

For very large factorials, you can use arrays. Arrays can store individual digits or libraries designed for big-number calculations and get the results.

4. What is the difference between a loop and recursion for factorial calculation?

A block of code is continually run in a loop until the factorial is reached. The recursion calls the function within itself. Both methods yield the same result but use different approaches.

5. How do I improve the efficiency of my factorial program?

If you want to optimize use of your memory, your code is typically going to be more memory-efficient using iterative methods like loops rather than recursion. You can also speed up your performance when computing large numbers using memoization - that is, storing previously computed results!

Read More Articles

Chat with us
Chat with us
Talk to career expert