30 lines
561 B
Common Lisp
30 lines
561 B
Common Lisp
// Calculate Fibonacci numbers
|
|
|
|
fn main() {
|
|
for num in 0..=30 {
|
|
print("fib(", num, ") = ", fib_iterative(num))
|
|
}
|
|
for num in 0..=30 {
|
|
print("fib(", num, ") = ", fib(num))
|
|
}
|
|
}
|
|
|
|
/// The classic recursive definition of fib()
|
|
fn fib(a: i64) -> i64 {
|
|
if a > 1 {
|
|
fib(a - 1) + fib(a - 2)
|
|
} else a
|
|
}
|
|
|
|
/// The classic iterative algorithm for fib()
|
|
fn fib_iterative(n: i64) -> i64 {
|
|
let mut a = 0;
|
|
let mut b = 1;
|
|
let mut c = 1;
|
|
for _ in 0..n {
|
|
a = b;
|
|
b = c;
|
|
c = a + b;
|
|
} else a
|
|
}
|