Naive recursive - factorial
public long factorial(int n) {
return n == 0 ? 1 : n * factorial(n - 1);
}
Naive recursive - fibonacci
public long fibonacci(int n) {
return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
}
Iterative - factorial
public long factorial(int n) {
long r = 1;
while (n > 0) r *= n--;
return r;
}
Iterative - fibonacci
public long fibonacci(int n) {
long a = 0;
long b = 1;
for (int i = 0; i < n; i++) {
long tmp = a;
a = b;
b += tmp;
}
return a;
}
Tail recursive - factorial
public long factorial(int n) {
return factorialHelper(n, 1);
}
private long factorialHelper(int n, long r) {
return n == 0 ? r : factorialHelper(n - 1, r * n);
}
Tail recursive - fibonacci
public long fibonacci(int n) {
return fibHelper(n, 0, 0, 1);
}
private long fibHelper(int n, int i, long a, long b) {
return i == n ? a : fibHelper(n, i + 1, b, a + b);
}