Factorial Program in Java : Easy Coding

What is Factorial of a positive number?

The factorial of a positive integer n, denoted by n!, is the product of all positive integers less than or equal to n.

n! = n * (n-1) * (n-2) *…*3*2*1

so, 5! = 5 * 4 * 3 * 2 * 1 = 120

Factorial Program in Java

Java Code

In the below, we will use build the factorial program in Java using two ways:

  1. Looping
  2. Recursion
package com.java.programs;

public class Factorial {      //Using Iterative way
    public static int factorial(int n) {
        if (n < 0)
            throw new IllegalArgumentException("Negative input not allowed");
        if (n == 0)
            return 1;
        if (n <= 2) {
            return n;
        }
        int output = 1;
        for (int i = 1; i <= n; i++) {
            output = output * i;
        }
        return output;
    }

    //Using Recursive way
    public static int factorialusingRecursion(int n) {
        if (n < 0)
            throw new IllegalArgumentException("Negative input not allowed");
        if (n == 0)
            return 1;
        if (n <= 2) {
            return n;
        }
        return n * factorialusingRecursion(n - 1);
    }

    public static void main(String[] args) {
        System.out.println(factorial(5));
        System.out.println(factorialusingRecursion(5));
        System.out.println(factorial(0));
        System.out.println(factorial(-1));

    }

}
120
120
1
Exception in thread "main" java.lang.IllegalArgumentException: Negative input not allowed
at com.java.programs.Factorial.factorial(Factorial.java:7)
at com.java.programs.Factorial.main(Factorial.java:35)

Conclusion: Factorial Program in Java

So, in this article, we learnt how to write a Factorial program in Java using for loop and recursion.

Related Articles

Simple Java Programs asked in Interviews

Leave a Reply

Your email address will not be published. Required fields are marked *