Last active
July 12, 2020 20:03
-
-
Save tolumide-ng/c9e26ea4127afd6a02462b80298ea21b to your computer and use it in GitHub Desktop.
Fibonacci Series with Rust
This file contains 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::io; | |
fn main() { | |
let mut number = String::new(); | |
println!("\nEnter a positive integer: "); | |
io::stdin().read_line(&mut number) | |
.expect("Failed to read line"); | |
let number: u32 = match number.trim().parse() { | |
Ok(num) => num, | |
Err(_) => 0, | |
}; | |
println!("{}", fibonacci(number)); | |
} | |
fn fibonacci(n: u32) -> u32 { | |
match n { | |
0 => 1, | |
1 => 1, | |
_ => fibonacci(n-1) + fibonacci(n-2), | |
} | |
} | |
// O(n) | |
pub fn fib2(n: usize) -> i32 { | |
let mut vec = vec![0, 1]; | |
for val in 2..=n { | |
let result = vec[val - 1] + vec[val - 2]; | |
vec.push(result); | |
} | |
vec[n] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment