Created
February 26, 2025 20:10
-
-
Save shawakash/612aae3952ef29aaef004cdd4efb32b8 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 num_bigint::BigUint; | |
| use num_traits::{One, Zero}; | |
| const FIB_LEN: usize = 1000; | |
| const FIBS: [u128; FIB_LEN] = create_fib_array(); | |
| const fn create_fib_array() -> [u128; FIB_LEN] { | |
| let mut arr = [0u128; FIB_LEN]; | |
| let mut i = 0; | |
| while i < FIB_LEN { | |
| arr[i] = match i { | |
| 0 => 0, | |
| 1 => 1, | |
| n => { | |
| let mut f1: u128 = 0; | |
| let mut f2: u128 = 1; | |
| let mut j = 2; | |
| while j <= n { | |
| let f3 = f1.wrapping_add(f2); | |
| f1 = f2; | |
| f2 = f3; | |
| j += 1; | |
| } | |
| f2 | |
| } | |
| }; | |
| i += 1; | |
| } | |
| arr | |
| } | |
| fn fib(num: u128) -> BigUint { | |
| if num == 0 { | |
| return BigUint::zero(); | |
| } | |
| if num == 1 { | |
| return BigUint::one(); | |
| } | |
| let mut f1 = BigUint::zero(); | |
| let mut f2 = BigUint::one(); | |
| for _ in 2..num { | |
| let f3 = &f1 + &f2; | |
| f1 = f2; | |
| f2 = f3; | |
| } | |
| return f2; | |
| } | |
| fn main() { | |
| println!("First 10 Fibonacci numbers:"); | |
| for (i, &fib) in FIBS.iter().enumerate() { | |
| println!("Fib({}) = {}", i, fib); | |
| } | |
| println!("\nSome larger Fibonacci numbers (runtime):"); | |
| println!("Fib(100) = {}", fib(5000)); | |
| println!("Fib(1000) = {}", fib(1000)); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment