Skip to content

Instantly share code, notes, and snippets.

@casweeney
Created August 15, 2024 15:32
Show Gist options
  • Save casweeney/028bc10d75fc59f46207cb88b52f8bc8 to your computer and use it in GitHub Desktop.
Save casweeney/028bc10d75fc59f46207cb88b52f8bc8 to your computer and use it in GitHub Desktop.
fn main() {
println!("{}", fibonacci(7));
}
// Using Recursion
// fn fibonacci(n: usize) -> usize {
// if (n < 2) {
// return n;
// }
// fibonacci(n - 1) + fibonacci(n - 2)
// }
// Using Loop
fn fibonacci(n: usize) -> usize {
if n < 2 {
return n;
}
let mut a = 0;
let mut b = 1;
let mut fib = 0;
let mut i = 2;
while i <= n {
fib = a + b;
a = b;
b = fib;
i+=1;
};
return fib;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment