💾 Archived View for gemini.mingmengtou.org › 2021-05-16-rust-fibonacci.gmi captured on 2023-01-29 at 03:00:14. Gemini links have been rewritten to link to archived content
⬅️ Previous capture (2021-11-30)
-=-=-=-=-=-=-
here so i can find it later. working through the rust book exercises.
2021-05-16 - rust programming language online book for learning rust.
2021-05-16 - summary and exercises related to common programming concepts.
i went with an iteration rather than recursion: two different versions. I prefer the second version myself.
// fibonacci // iterative solution with sequence starting at 0 // fn fibonacci( seq: u64 ) -> u64 { let mut last_last = 1; let mut last = 1; let mut result = 1; if seq == 1 { return 0 } else if seq == 2 { return 1 } else { for _i in 3..seq { result = last_last + last; last_last = last; last = result; } } result } fn fibonacci2( seq: u64 ) -> u64 { let mut last_last = 1; let mut last = 1; let mut result = 1; match seq { 1 => result = 0, 2 => result = 1, _ => { for _i in 3..seq { result = last_last + last; last_last = last; last = result; } } } result }
and to test it:
// fibonacci // for fib_num in 1..=30 { println!("fibonacci {} : {}:", fib_num, fibonacci(fib_num)); }; // // fibonacci2 // for fib_num in 1..=40 { println!("fibonacci {} : {}:", fib_num, fibonacci2(fib_num)); };
does what it says on the tin!
---
return to gemini.mingmengtou.org index page.
---
neil.gemini@mingmengtou.org
content licensed CC-BY-SA 4.0 unless stated.