What is the factorial in java
The factorial of a positive integer is the product of all positive integers less than it and itself.need to note that the factorial of 0 is 1.we use n! to represent the factorial of an integer number n.
In other words,n!=1x2x3x4x…xn.also can use recursion to defined a factorial as 0!=1, n!=(n-1)!xn.
factorial using recursion in java
Let’s write a java simple recursion program to get the factorial of given numbes from 0 to 10:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class MainClass { public static void main(String args[]) { for (int counter = 0; counter <= 10; counter++){ System.out.printf("%d! = %d\n", counter, factorial(counter)); } } public static long factorial(long number) { if (number <= 1) return 1; else return number * factorial(number - 1); } } |
output
1 2 3 4 5 6 7 8 9 10 11 |
0! = 1 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 8! = 40320 9! = 362880 10! = 3628800 |
factorial using loop in java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public class MainClass { public static void main(String args[]) { for (int counter = 0; counter <= 10; counter++){ System.out.printf("%d! = %d\n", counter, factorial(counter)); } } public static long factorial(long number) { int i,fact=1; for(i=1;i<=number;i++){ fact=fact*i; } return fact; } } |
output
1 2 3 4 5 6 7 8 9 10 11 |
0! = 1 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 8! = 40320 9! = 362880 10! = 3628800 |