Iterative:
private static long iFactorial (long n) {
if (n <= 1) { return 1; }
long val = 1;
for (long i = 2; i <= n; i++) {
val *= i;
}
return val;
}
Recursive:
private static long rFactorial (long n) {
if (n <= 1) { return 1; }
return n * rFactorial(n - 1);
}
Recursive is more succinct… but let’s test their performance!
Iterative:
private static long iFib (long n) {
long prev = 0; long cur = 1; long next;
for (long count = 1; count < n; count++) {
next = prev + cur;
prev = cur;
cur = next;
}
return cur;
}
Recursive:
private static long rFib (long n) {
if (n <= 2) return 1;
return rFib(n-1) + rFib(n-2);
}
Why is this:
private static long rFactorial (long n) {
if (n <= 1) { return 1; }
return n * rFactorial(n - 1);
}
so much more efficient than this:
private static long rFib (long n) {
if (n <= 2) return 1;
return rFib(n-1) + rFib(n-2);
}
private static long rFactorial (long n) {
if (n <= 1) { return 1; }
return n * rFactorial(n - 1);
}
private static long rFib (long n) {
if (n <= 2) return 1;
return rFib(n-1) + rFib(n-2);
}
Recall the Tower of Hanoi Puzzle:
Goal. Move all disks from peg 1 to peg 3
All disks on first peg
Move one disk at a time
Cannot place a larger disk atop a smaller disk
To move all disks from peg 1 to peg 3
Want:
Move disk from peg 1 to peg 2
Move disk from peg 1 to peg 3
Move disk from peg 2 to peg 3
How do we design the program?
Hints:
Discuss!