Skip to content

Instantly share code, notes, and snippets.

@uztbt
Created April 9, 2022 13:17
Show Gist options
  • Save uztbt/1c9dd0a8f30aea8b3eb447033d2fd89f to your computer and use it in GitHub Desktop.
Save uztbt/1c9dd0a8f30aea8b3eb447033d2fd89f to your computer and use it in GitHub Desktop.
An exercise of Chaper 3 of the Book
use std::io;
fn main() {
loop {
println!("Input a number!");
let mut nth = String::new();
io::stdin()
.read_line(&mut nth)
.expect("Error in reading nth");
let nth: u32 = match nth.trim().parse() {
Ok(n) => n,
Err(_) => continue,
};
let ans = fib(nth);
println!("{}th Fibonacci number is {}", nth, ans);
}
}
// Returns the nth number of the Fibonacci sequence.
fn fib(n: u32) -> u64 {
match n {
0 => 1,
1 => 1,
m => fib(m - 1) + fib(m - 2),
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment