How to calculate the factorial of a given number in java?

The multiplication of all positive integers which are less than or equal to the given positive number is called the factorial of that given integer number.

Example #1, The factorial of the number 5 can be calculated as follow:

1 * 2 * 3 * 4 * 5 = 120

Example #2, The factorial of the number 8 can be calculated as follow:-

1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 = 40320

Solution #1: Calculate the factorial using Recursion

FactorialCalculation.java

package com.javacodepoint.programs;

import java.util.Scanner;

public class FactorialCalculation {

	public static void main(String[] args) {

		// Taking input from the user to calculate factorial for a given number

		System.out.println("Enter number to calculate factorial:");

		// Reading user input using Scanner object
		int number = new Scanner(System.in).nextInt();
		
		if(number < 0) {
			System.out.println("Please enter only positive interger number");
			return;
		}
		
		System.out.println("Factorial of "+number+" is : "+clculateFactorial(number));

	}
		
	/* 
	 * Method to calculate factorial using recursion
	 */
	
	public static int clculateFactorial(int number) {
		
		if(number == 0) {
			return 1;
		}
		
		return number * clculateFactorial(number-1);
	}
}

OUTPUT:

Enter number to calculate factorial:
5
Factorial of 5 is : 120

Solution #2: Without Using Recursion

FactorialCalculation.java

package com.javacodepoint.programs;

import java.util.Scanner;

public class FactorialCalculation {

	public static void main(String[] args) {

		// Taking input from the user to calculate factorial for a given number

		System.out.println("Enter number to calculate factorial:");

		// Reading user input using Scanner object
		int number = new Scanner(System.in).nextInt();
		
		if(number < 0) {
			System.out.println("Please enter only positive interger number");
			return;
		}
		
		System.out.println("Factorial of "+number+" is : "+clculateFactorial(number));

	}
		
	/* 
	 * Method to calculate factorial without recursion
	 */
	
	public static int clculateFactorial(int number) {
		
		int factorial = 1;
		
		while(number != 0){
			
			factorial = factorial * number ;
			number--;
		}
		
		return factorial;
	}
}

OUTPUT:

Enter number to calculate factorial:
6
Factorial of 6 is : 720

Java logical programs list


Java Basic Programs

Java Programs based on the Collection Framework