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 {
|
2024-07-26 11:13:59 +00:00
|
|
|
println("fib(", num, ") = ", fibit(num))
|
2024-04-19 15:49:25 +00:00
|
|
|
}
|
2024-02-29 22:48:09 +00:00
|
|
|
for num in 0..=30 {
|
2024-07-26 10:13:52 +00:00
|
|
|
println("fib(", num, ") = ", fib(num))
|
2024-02-29 22:48:09 +00:00
|
|
|
}
|
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()
|
2024-07-26 11:13:59 +00:00
|
|
|
fn fibit(n: i64) -> i64 {
|
2024-04-19 15:49:25 +00:00
|
|
|
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
|
|
|
}
|