64 lines
1.6 KiB
Rust
64 lines
1.6 KiB
Rust
extern crate separator;
|
|
|
|
use separator::Separatable;
|
|
|
|
use std::io;
|
|
use std::u128;
|
|
|
|
///! Calculate a number in the fibonacci sequence,
|
|
///! using a lookup table for better worst-case performance.
|
|
///
|
|
/// Can calculate up to 186 using native unsigned 128 bit integers.
|
|
fn fibonacci(n: usize, table: &mut Vec<u128>) -> Option<u128> {
|
|
match table.get(n) {
|
|
Some(x) => Some(*x),
|
|
None => {
|
|
let a = fibonacci(n - 1, table)?;
|
|
let b = fibonacci(n - 2, table)?;
|
|
|
|
// Check for overflow when adding
|
|
let attempt = a.checked_add(b);
|
|
|
|
if let Some(current) = attempt {
|
|
table.insert(n, current);
|
|
}
|
|
|
|
attempt
|
|
}
|
|
}
|
|
}
|
|
|
|
fn main() {
|
|
// The lookup table for previously calculated values
|
|
let mut table: Vec<u128> = vec![0, 1, 1, 2, 3, 5];
|
|
|
|
println!("Fibonacci calculator.");
|
|
println!("Any non-number will exit.");
|
|
|
|
loop {
|
|
println!("\nWhich index in the sequence to calculate?");
|
|
|
|
let mut index = String::new();
|
|
|
|
io::stdin().read_line(&mut index)
|
|
.expect("Failed to read line");
|
|
|
|
let index = match index.trim().parse() {
|
|
Ok(num) => num,
|
|
Err(_) => break, // Exit on non-number
|
|
};
|
|
|
|
println!("Calculating number for index: {}", index);
|
|
|
|
match fibonacci(index, &mut table) {
|
|
Some(calculated) => {
|
|
println!("The Fibonacci number at index: {} is {}", index, calculated.separated_string());
|
|
},
|
|
None => {
|
|
println!("Calculation overflow. The factorial base was too large.");
|
|
}
|
|
}
|
|
|
|
}
|
|
}
|