2023-10-30 05:23:43 +00:00
|
|
|
// Calculate Fibonacci numbers
|
|
|
|
|
2024-02-29 22:48:09 +00:00
|
|
|
fn main() {
|
2024-04-19 15:49:25 +00:00
|
|
|
for num in 0..=30 {
|
|
|
|
print("fib(", num, ") = ", fib_iterative(num))
|
|
|
|
}
|
2024-02-29 22:48:09 +00:00
|
|
|
for num in 0..=30 {
|
|
|
|
print("fib(", num, ") = ", fib(num))
|
|
|
|
}
|
2023-10-30 05:23:43 +00:00
|
|
|
}
|
|
|
|
|
2024-04-19 15:49:25 +00:00
|
|
|
/// The classic recursive definition of fib()
|
2024-02-29 22:48:09 +00:00
|
|
|
fn fib(a: i64) -> i64 {
|
2023-10-30 05:23:43 +00:00
|
|
|
if a > 1 {
|
|
|
|
fib(a - 1) + fib(a - 2)
|
2024-04-19 15:49:25 +00:00
|
|
|
} 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
|
2023-10-30 05:23:43 +00:00
|
|
|
}
|