forked from dr-cs/intro-oop-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFac.java
More file actions
70 lines (63 loc) · 1.51 KB
/
Fac.java
File metadata and controls
70 lines (63 loc) · 1.51 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
public class Fac {
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
System.out.println("facLoop("+n+")=" + facLoop(n));
System.out.println("facTail("+n+")=" + facTail(n));
System.out.println("fac("+n+")=" + fac(n));
}
/**
* The factorial of n is n * facotrial of n-1 for n > 1, otherwise 1.
*/
public static int fac(int n) {
if (n <= 1) {
return 1;
} else {
return n * fac(n - 1);
}
}
public static int facLoop(int n) {
int factorial = 1;
for (int x = n; x > 0; x--) {
factorial *= x;
}
return factorial;
}
/**
* A tail recursive factorial function using a recursive helper method
* to create the iterations.
*/
public static int facTail(int n) {
return facIter(n, 1);
}
/**
* Designed to be called by facIter. accum accumulates the answer as
* n decrements to the base case.
*/
private static int facIter(int n, int accum) {
if (n <= 1) {
return accum;
} else {
return facIter(n - 1, n * accum);
}
}
/*
Iterative process
facIter(5);
facIter(4, 5);
facIter(3, 20);
facIter(2, 60);
facIter(1, 120);
120
Recursive process
fac(5);
5 * fac(4);
5 * 4 * fac(3);
5 * 4 * 3 * fac(2);
5 * 4 * 3 * 2 *fac(1);
5 * 4 * 3 * 2 * 1;
5 * 4 * 3 * 2;
5 * 4 * 6;
5 * 24;
120;
*/
}