In this article, we will discuss different ways to find factorial of a number in Java.
Factorial of a number is obtained from the result of multiplying a series of descending natural numbers.
Java Factorial : Iterative approach
The following algorithm generates factorial of a number using a while loop. The same could be rewritten using other looping constructs.
long fact = 1;
while (num > 0) {
fact *= num--;
}
Here is the complete program for the same :
package com.topjavatutorial; import java.util.Scanner; public class Factorial { public static void main(String[] args) { System.out.println("Enter a number: "); Scanner sc = new Scanner(System.in); int num = sc.nextInt(); sc.close(); System.out.println("Factorial of " + num + " = " + factorial(num)); } private static long factorial(int num) { long fact = 1; while (num > 0) { fact *= num--; } return fact; } }
Output:
Enter a number:
6
Factorial of 6 = 720
You could also use a do.. while or for loop for the same.
Here is how to calculate factorial using for loop :
private static long factorial(int num) { long fact = 1; for (int i = num - 1; i >= 1; i--) { fact *= num--; } return fact; }
Java Factorial using recursion
Factorial of a number can be expressed recursively as follows :
n! = n * (n-1)!
= n * (n-1) * (n-2)!
= n * (n-1) * (n-2) * (n-3)!
…
Here is the program for the same :
package firstpackage; public class FactorialUsingRecursion { public static void main(String[] args) { System.out.println("5! = " + factorial(5)); } private static long factorial(int num){ if(num==1) return 1; else return num*factorial(num-1); } }
Output :
5! = 120
© 2017 – 2018, https:. All rights reserved. On republishing this post, you must provide link to original post