Last active
August 29, 2015 14:02
-
-
Save Antti/10e325e48c9f2943eb20 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
| extern crate num; | |
| use num::bigint::{BigUint,ToBigUint}; | |
| // pub struct Fib { | |
| // current: uint, | |
| // next: Option<uint> | |
| // } | |
| // impl Fib { | |
| // fn new() -> Fib { | |
| // Fib{current: 0, next: Some(1)} | |
| // } | |
| // } | |
| // impl Iterator<uint> for Fib { | |
| // fn next(&mut self) -> Option<uint> { | |
| // match self.next { | |
| // Some(next) => { | |
| // let current = self.current; | |
| // self.current = next; | |
| // self.next = next.checked_add(¤t); | |
| // Some(current) | |
| // }, | |
| // None => None | |
| // } | |
| // } | |
| // } | |
| #[deriving(Show)] | |
| pub struct FibBigInt { | |
| current: BigUint, | |
| next: BigUint | |
| } | |
| impl FibBigInt { | |
| fn new() -> FibBigInt { | |
| FibBigInt{current: 0u64.to_biguint().unwrap(), next: 1u64.to_biguint().unwrap()} | |
| } | |
| } | |
| impl Iterator<BigUint> for FibBigInt { | |
| fn next(&mut self) -> Option<BigUint> { | |
| use std::mem::replace; | |
| let new_next = self.current.add(&self.next); | |
| let old_next = replace(&mut self.next, new_next); | |
| Some(replace(&mut self.current, old_next)) | |
| } | |
| } | |
| fn recursive_fib(n: uint) -> uint{ | |
| if n < 2 { | |
| n | |
| } | |
| else{ | |
| recursive_fib(n-2) + recursive_fib(n-1) | |
| } | |
| } | |
| fn main() { | |
| let args = std::os::args(); | |
| let n = match args.len(){ | |
| 1 => 10, | |
| 2 => from_str::<uint>(args.get(1).as_slice()).unwrap_or(10), | |
| x if x > 2 =>fail!("usage: {} [fib_number]", args.get(0)), | |
| _ => unreachable!() | |
| }; | |
| // let (number, fib) = Fib::new().take(n as uint).fold((0, 0),|acc, item| (acc.val0()+1, item) ); | |
| // println!("My {}th fib nuber is: {}", number, fib); | |
| let (number, fib) = FibBigInt::new().take(n as uint).fold((0u64, 0u64.to_biguint().unwrap()),|acc, item| (acc.val0()+1, item) ); | |
| println!("My {}th Bigfib nuber is: {}", number, fib); | |
| // println!("Recursive fib: {}",recursive_fib(n)); | |
| // println!("{}",recursive_fib(40)); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment