for int(i = 0; i < max; i++) {
// do something
}
public int doSomething(int n) {
// some code
doSomething(n - 1); // recursive function call
// some more code
return something;
}
For a positive integer $n$, the factorial function, $f(n) = n!$ is defined to be:
Compute some factorials!
For any $n \geq 2$, we have
This is a recursive formula!
private static int factorial(int n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
private static int factorial(int n) {
if (n == 1) {
return 1;
}
return n * factorial(n - 1);
}
Compute factorial(4)
by hand!
The Fibonacci numbers are the sequence of numbers
$1, 1, 2, 3, 5, 8, 13, 21, \ldots$
where each number is the sum of the previous two.
Activity. Write a method that computes the $n$-th Fibonacci number for a positive integer (long
) $n$.
Question. Which is better?
What makes recursive Fibonacci slow, while recursive factorial is fairly fast?
private static long fib (long n) {
if (n <= 2)
return 1;
return fib(n-1) + fib(n-2);
}
private static int factorial(int n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
Three morals, three questions