-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRecursiveFunctions.java
More file actions
38 lines (32 loc) · 930 Bytes
/
RecursiveFunctions.java
File metadata and controls
38 lines (32 loc) · 930 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
package recursion;
public class RecursiveFunctions {
public static int findSum(int n) {
if (n == 0) return 0;
if (n == 1) return 1;
return n + findSum(n - 1);
}
public static int findSumTailRec(int n, int a) {
if (n == 0) return a;
return findSumTailRec(n - 1, n + a);
}
public static int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}
public static int factorialTailRec(int n, int a) {
if (n == 0) return a;
return factorialTailRec(n - 1, n * a);
}
public static int fibonacci(int n) {
if (n <= 1)
return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
public static int fibonacciTailRec(int n, int a, int b) {
if (n == 0)
return a;
if (n == 1)
return b;
return fibonacciTailRec(n - 1, b, a + b);
}
}