Factorial of a Number in Java

Yuvaraj
2 min readAug 5, 2024

--

Basic Java Program

A factorial is a mathematical function denoted by an exclamation mark (!). It is defined for a non-negative integer n as the product of all positive integers less than or equal to n.

The factorial of n, written as n!, is calculated as:

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

For example:

  • 5! = 5 × 4 × 3 × 2 × 1 = 120
  • 4! = 4 × 3 × 2 × 1 = 24
  • 3! = 3 × 2 × 1 = 6
  • 2! = 2 × 1 = 2
  • 1! = 1
  • 0! = 1 (by definition)
Factorial of numbers
import java.util.Scanner;

public class Factorial {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");
int number = scanner.nextInt();

int factorial = 1;

for (int i = 1; i <= number; i++) {
factorial *= i; // factorial = factorial * i;
}

System.out.println("The factorial of " + number + " is " + factorial);

scanner.close(); // Close the Scanner object to free up resources
}
}

// Output:
/* Enter a number: 6
The factorial of 6 is 720 */

The line int factorial = 1; is important because:

  1. Multiplicative Identity:
  • In multiplication, multiplying by 1 doesn’t change the value.
  • For example, 5 * 1 = 5. So, starting with 1 means our first multiplication is correct and doesn’t affect the result.

2. Starting Point for Multiplication:

  • If we start with factorial set to 0, any number multiplied by 0 will always be 0.
  • For example, 5 * 0 = 0. So, if we start with 0, the result will always be 0, which is wrong.
  • By starting with 1, we can correctly multiply all numbers in the sequence to get the factorial.

Example:

To calculate the factorial of 4 (4!), the steps are:

  1. Start with factorial = 1.
  2. Multiply factorial by 1 → factorial = 1 * 1 = 1.
  3. Multiply factorial by 2 → factorial = 1 * 2 = 2.
  4. Multiply factorial by 3 → factorial = 2 * 3 = 6.
  5. Multiply factorial by 4 → factorial = 6 * 4 = 24.

So, 4! = 24.

Starting with 1 ensures that these multiplications work correctly. If we started with 0, every step would result in 0.

The statement factorial *= i; is a shorthand way of writing factorial = factorial * i;.

  • factorial is a variable that holds the current value of the factorial calculation.
  • *= is a compound assignment operator that means "multiply the current value by the specified value and store the result back in the variable."
  • i is the loop control variable that changes with each iteration of the loop.

--

--