Created
March 21, 2023 19:59
-
-
Save dnutiu/6153188fe2155caa6a76f83cca319d56 to your computer and use it in GitHub Desktop.
An iterative & recursive implementation of Fibbonaci in 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
fn fib(n: i32) { | |
let mut a: u128 = 1; | |
let mut b = 1; | |
for i in 0..n { | |
if i == 0 || i == 1{ | |
print!("{} ", a); | |
continue | |
} | |
let c = a; | |
a = b; | |
b = a + c; | |
print!("{} ", b) | |
} | |
println!() | |
} | |
fn fib_r(n: i32) -> i32{ | |
if n == 0 { | |
return 0; | |
} | |
if n == 1 { | |
return 1; | |
} | |
let num = fib_r(n - 1) + fib_r(n - 2); | |
return num; | |
} | |
fn print_fib_r_2(start: i32, stop: i32, cache: &mut Vec<i32>, out_result: &mut Vec<i32>) { | |
let mut value: i32 = cache[start as usize]; | |
if value == -1 { | |
value = fib_r(start); | |
cache[start as usize] = value; | |
} | |
out_result[(start - 1) as usize] = value; | |
if start < stop { | |
print_fib_r_2(start + 1, stop, cache, out_result) | |
} | |
} | |
fn print_fib_r(n: i32, cache: &mut Vec<i32>) -> Vec<i32> { | |
let mut result: Vec<i32> = Vec::new(); | |
for i in 0..n { | |
result.push(-1); | |
} | |
print_fib_r_2(1, n, cache, &mut result); | |
return result | |
} | |
fn main() { | |
fib(15); | |
let mut cache = Vec::new(); | |
for _ in 0..100 { | |
cache.push(-1) | |
} | |
let data = print_fib_r(25, &mut cache); | |
println!(); | |
for i in data { | |
print!("{} ", i) | |
} | |
let data = print_fib_r(40, &mut cache); | |
println!(); | |
for i in data { | |
print!("{} ", i) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment