Skip to content

Instantly share code, notes, and snippets.

@hseeberger
Last active July 27, 2023 11:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hseeberger/45572df5dd7e3f6f950c78204ba72055 to your computer and use it in GitHub Desktop.
Save hseeberger/45572df5dd7e3f6f950c78204ba72055 to your computer and use it in GitHub Desktop.
Fibonacci numbers in Rust
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