Skip to content

Instantly share code, notes, and snippets.

@sibu-github
Created March 31, 2022 19:24
Show Gist options
  • Save sibu-github/0c83ba96a195eecf4b8b5839425e67da to your computer and use it in GitHub Desktop.
Save sibu-github/0c83ba96a195eecf4b8b5839425e67da to your computer and use it in GitHub Desktop.
Get nth Fibonacci number in Rust
fn fibonacci(term: u64) -> u64 {
let (_, tot) = (0..=term).fold((0_u64, 1_u64), |acc, t| {
match t {
0 => (0_u64, 0_u64),
1 => (0, 1_u64),
2 => (1, 1_u64),
_ => {
let (prev, tot) = acc;
(tot, tot + prev)
}
}
});
tot
}
fn main() {
let n = 5;
println!("{}th fibonacci value is {}", n, fibonacci(n));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment