Saturday, June 11, 2022

Factorial Program in Java

In this post we'll see a Java program to calculate factorial of a given number.

If we go by the definition- Factorial of a non-negative integer n is product of all positive integers less than or equal to n.

As example

4! = 4 X 3 X 2 X 1 = 24

If you see here you need to multiply every time by the number which is one less than the previous one until you reach 1, which can be considered base case. That makes factorial program in Java using recursion a very good example for learning recursive programming. In fact calculating factorial using recursion is the first program many people will do while learning recursion apart from another program How to reverse a string in Java using recursion

If there is a recursive solution for any problem then there is an iterative solution too. In this post we'll see factorial program using both recursive and iterative logic.

Factorial program in Java using Iteration

import java.util.Scanner;

public class FactorialItr {

 public static void main(String[] args) {
    // get input from user
    Scanner input = new Scanner(System.in);
    System.out.println("Enter a number: ");
    int num = input.nextInt();
    int fact = calculateFactorial(num);
    System.out.println("Factorial of " + num + " is " + fact); 
 }
 
 private static int calculateFactorial(int num){
  int fact = 1;
  for(int i = num; i >= 1; i--){
    fact = fact * i; 
  }
  return fact;  
 }
}

Output

Enter a number: 
5
Factorial of 5 is 120

Logic here is to take input from console and calculate factorial of that number using for loop that ranges from number till 1 and within the loop keep multiplying the result with the loop counter.

Factorial program in Java using Recursion

import java.util.Scanner;

public class Factorial {
 public static void main(String[] args) {
    // get input from user
    Scanner input = new Scanner(System.in);
    System.out.println("Enter a number: ");
    int num = input.nextInt();
    int fact = calculateFactorial(num);
    System.out.println("Factorial of " + num + " is " + fact); 
 }
 
  private static int calculateFactorial(int num){
    // base case (exit recursion)
    if(num == 1){
      return 1;
    }else{
      return num * calculateFactorial(num - 1);
    }  
  }
}

Output

Enter a number: 
4
Factorial of 4 is 24

Here again the user is asked to enter a number then the same method is called recursively using passed number minus one every time. Base case here is when number becomes 1. Since factorial of 0 and 1 both is 1 so both can be used as base cases.

A word of caution here though, if you are trying to get a factorial of a number more than 16 or 17 then take the type as double or BigInteger otherwise you will get an overflow error.

That's all for this topic Factorial Program in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Java Program to Display Prime Numbers
  2. How to Display Pyramid Patterns in Java - Part1
  3. Fibonacci Series Program in Java
  4. Arrange Non-Negative Integers to Form Largest Number - Java Program
  5. Swap or Exchange Two Numbers Without Using Any Temporary Variable Java Program

You may also like-

  1. How to Convert Date to String in Java
  2. Matrix Multiplication Java Program
  3. Find All Permutations of a Given String Java Program
  4. If Given String Sub-Sequence of Another String in Java
  5. Abstraction in Java
  6. Dependency Injection in Spring Framework
  7. Why wait(), notify() And notifyAll() Methods Are in Object Class And Not in Thread Class
  8. final Vs finally Vs finalize in Java

No comments:

Post a Comment