forked from java8/Java8InAction
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRecursion.java
More file actions
39 lines (30 loc) · 1023 Bytes
/
Recursion.java
File metadata and controls
39 lines (30 loc) · 1023 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package lambdasinaction.chap13;
import java.util.stream.LongStream;
public class Recursion {
public static void main(String[] args) {
System.out.println(factorialIterative(5));
System.out.println(factorialRecursive(5));
System.out.println(factorialStreams(5));
System.out.println(factorialTailRecursive(5));
}
public static int factorialIterative(int n) {
int r = 1;
for (int i = 1; i <= n; i++) {
r*=i;
}
return r;
}
public static long factorialRecursive(long n) {
return n == 1 ? 1 : n*factorialRecursive(n-1);
}
public static long factorialStreams(long n){
return LongStream.rangeClosed(1, n)
.reduce(1, (long a, long b) -> a * b);
}
public static long factorialTailRecursive(long n) {
return factorialHelper(1, n);
}
public static long factorialHelper(long acc, long n) {
return n == 1 ? acc : factorialHelper(acc * n, n-1);
}
}