Before jumping into the code for Java Program Factorial let’s define what a factorial is?
Definition: A factorial is a function that multiplies a number by every number below it. For example 5!= 5*4*3*2*1=120. The function is used, among other things, to find the number of way ānā objects can be arranged. Factorial.
Java Program For Factorial Code
public class Factorial {
public static void main(String[] args) {
int n = 5; // input
int i;
double fact = 1;
System.out.print(n+"! = ");
for(i = 1; i < n; i++) {
fact *= i;
System.out.print(i+" x ");
}
fact *= i;
System.out.print(i+" = "+ fact);
}
}
OUTPUT
5! = 1 x 2 x 3 x 4 x 5 = 120.0
EXPLANATION
Here we use a for loop to iterate from 1 to the given number and store their product in fact. It is a pretty straightforward solution to this problem. But the problem remains unsolved. Observing keenly we see that we don’t validate the input at all! We must adjust our program to handle negative inputs. Here’s how we can do it?
public class Factorial {
public static void main(String[] args)throws WrongInputException{
try {
int n = -5; // input
if(n<0)
throw new WrongInputException("n cannot be less than zero!");
int i;
double fact = 1;
System.out.print(n+"! = ");
for(i = 1; i < n; i++) {
fact *= i;
System.out.print(i+" x ");
}
fact *= i;
System.out.print(i+" = "+ fact);
}catch(WrongInputException w) {
System.out.println("*******Program ends*******");
}
}
}
class WrongInputException extends Exception{
public WrongInputException(String msg) {
System.out.println(msg);
}
}
OUTPUT
n cannot be less than zero!
*******Program ends*******
EXPLANATION
To handle the error we create a custom WrongInputException. Now throw it when input is less than 0. The entire code is wrapped in a try-catch block. Therefore, as soon as the error is thrown the catch block executes and marks the end of the program.
Still, the input part of the code seems unsatisfactory.
Let’s improve it using the Scanner class in Java to accept console-based user input.
Improved Java Factorial Program
import java.util.Scanner;
public class Factorial {
public static void main(String[] args)throws WrongInputException{
try {
Scanner sc = new Scanner(System.in);
System.out.println("enter number to calculate factorial: ");
int n = sc.nextInt();// input
if(n<0)
throw new WrongInputException("N cannot be less than zero!");
int i;
double fact = 1;
System.out.print(n+"! = ");
for(i = 1; i < n; i++) {
fact *= i;
System.out.print(i+" x ");
}
fact *= i;
System.out.print(i+" = "+ fact);
}catch(WrongInputException w) {
System.out.println("*******Program ends*******");
}
}
}
class WrongInputException extends Exception{
public WrongInputException(String msg) {
System.out.println(msg);
}
}
OUTPUT
enter number to calculate factorial:
6
6! = 1 x 2 x 3 x 4 x 5 x 6 = 720.0
Java Program for Factorial with Recursion
Using recursion Factorial can be easily implemented in Java just by returning the number n multiplied with a factorial of (n-1). We use a base case that if n is less or equal to 1 we return 1. This resolves the call stack step by step from fact(1) to fact(n) . Ultimately producing the desired result.
public class FactorialRecursion {
static int fact(int n) {
if(n <= 1)
return 1;
return n * fact(n-1);
}
public static void main(String[] args) {
int n = 5;
System.out.println("factorial of "+n+": "+fact(n));
}
}
OUTPUT
factorial of 5: 120
Java Program of Factorial Using Tail End Recursion
Benefits of tail-recursion
- Uses very few stack-frames for tail-recursive calls.
- Consumes less memory.
- No more StackOverflowException issues.
We can improve the Java Program for Recursion using tail-end recursion. Hers how we do it.
public class FactorialRecursion {
static int fact(int n, int a) {// Tail-end Recursion
if(n <= 1)
return a; // a acts as the accumulator
return fact(n-1,a*n);
}
public static void main(String[] args) {
int n = 3;
System.out.println("factorial of "+n+": "+fact(n,1));
}
}
OUTPUT
factorial of 3: 6
In Tail-end Recursion the last operation on the recursive function is the recursive call. Hence no need to maintain a call stack like the previous code for the statement n*fact(n-1).