-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRecursion.java
More file actions
52 lines (45 loc) · 906 Bytes
/
Recursion.java
File metadata and controls
52 lines (45 loc) · 906 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
40
41
42
43
44
45
46
47
48
49
50
51
52
public class Recursion {
public static int recursion(int count) {
if (count == 1) {
return 1;
} else {
return count * recursion(count - 1);
}
}
/**
* Use recursion realize Fab.
*/
public static int fab(int count) {
if (count < 0) {
System.out.println("invalid args");
return -1;
} else if (count ==1 || count ==2) {
return 1;
} else {
return fab(count - 1) + fab(count - 2);
}
}
public static int fabCount(int count) {
if (count < 0) {
System.out.println("invalid args");
return -1;
} else if (count == 1 || count ==2) {
return 1;
} else {
int f1 = 1;
int f2 = 1;
int f = 0;
for (int i = 0; i < count-2; i++) {
f = f1 + f2;
f1 = f2;
f2 = f;
}
return f;
}
}
public static void main(String[] args) {
System.out.println(recursion(5));
System.out.println(fab(5));
System.out.println(fabCount(5));
}
}