Pages

Factorial of a number

Find Factorial of given number

  • The product of an integer and all the integers below it can be referred as factorial.

Ex: 3! = 3*2*1
import java.util.stream.LongStream;

public class Factorial {

public static void main(String[] args) {
// 4!=4*3*2*1
int n = 5;
int f = 1;
for (int i = 1; i <= n; i++) {
f = f * i;
}


System.out.println(
"Factorial of given number using for loop=" + f);

long u = LongStream.rangeClosed(1, n).reduce(1, (long a, long b) -> a * b);
System.out.println("Factorial of given number using java 8=" + u);


System.out.println(
"Factorial of given number using recursive=" + factRecursive(n));
}

public static int factRecursive(int n) {
return n == 1 ? 1 : n * factRecursive(n - 1);
}

}
Output:
Factorial of a number
Factorial of a number

Please comment below to feedback or ask questions.

No comments:

Post a Comment

Please comment below to feedback or ask questions.