Advertisement
Guest User

Untitled

a guest
Apr 24th, 2019
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.14 KB | None | 0 0
  1. use std::io::{stdin, stdout, Write};
  2.  
  3. use std::sync::Mutex;
  4.  
  5. use lazy_static::lazy_static;
  6.  
  7. lazy_static! {
  8.     static ref CACHE: Mutex<Vec<u64>> = Mutex::new(vec![1, 1]);
  9. }
  10.  
  11. fn main() {
  12.     loop {
  13.         print!("Enter a positive integer: ");
  14.         stdout().flush().expect("could not flush buffer");
  15.  
  16.         let mut input = String::new();
  17.         let read = stdin().read_line(&mut input).expect("failed to read line");
  18.         // EOF
  19.         if read == 0 || input.trim() == "quit" {
  20.             break;
  21.         }
  22.  
  23.         let num: usize = match input.trim().parse() {
  24.             Ok(num) => num,
  25.             Err(e) => {
  26.                 println!("error parsing integer: {}", e);
  27.                 continue;
  28.             }
  29.         };
  30.  
  31.         println!("fibonacci of {} is {}", num, fib(num));
  32.     }
  33. }
  34.  
  35. fn fib(n: usize) -> u64 {
  36.     CACHE.lock().unwrap().reserve(n);
  37.     if CACHE.lock().unwrap().len() <= n {
  38.         let result = match n {
  39.             0 => 1,
  40.             1 => 1,
  41.             _ => fib(n - 1) + fib(n - 2)
  42.         };
  43.         CACHE.lock().unwrap().push(result);
  44.     }
  45.     return CACHE.lock().unwrap()[n];
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement