Last active
July 27, 2023 11:25
-
-
Save hseeberger/45572df5dd7e3f6f950c78204ba72055 to your computer and use it in GitHub Desktop.
Fibonacci numbers in Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::iter; | |
fn main() { | |
println!("{:?}", fibs_iter().skip(42).next().unwrap()); | |
println!("{}", fibs_recursive(42)); | |
} | |
fn fibs_iter() -> impl Iterator<Item = u128> { | |
let mut a = 0; | |
let mut b = 1; | |
let fibs = iter::from_fn(move || { | |
let next = a + b; | |
a = b; | |
b = next; | |
Some(next) | |
}); | |
vec![0, 1].into_iter().chain(fibs) | |
} | |
fn fibs_recursive(n: usize) -> u64 { | |
match n { | |
0 => 0, | |
1 => 1, | |
_ => fibs_recursive(n - 2) + fibs_recursive(n - 1) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment