Another update from ingydotnet^djgoku
This commit is contained in:
parent
91df62d461
commit
948b86eafa
7604 changed files with 108452 additions and 22726 deletions
|
|
@ -1,66 +1,30 @@
|
|||
// Works with 0.13.0-dev (f673e9841)
|
||||
fn fib<F>(n: i64, f: F) -> (i64, i64) where F: Fn(i64) {
|
||||
if n < 0 {
|
||||
// Let these variables be mutated, otherwise too slow
|
||||
let mut n1:i64 = 0;
|
||||
let mut n2:i64 = -1;
|
||||
let mut i:i64 = 0;
|
||||
let mut tmp:i64;
|
||||
#![feature(zero_one)]
|
||||
use std::num::One;
|
||||
use std::ops::Add;
|
||||
|
||||
while i > n {
|
||||
f(n1);
|
||||
tmp = n1-n2;
|
||||
if tmp > 0 && n2 > 0 { //Detect overflow
|
||||
println!("\nReached the limit of i64, halting");
|
||||
return (n1, i);
|
||||
}
|
||||
n1 = n2;
|
||||
n2 = tmp;
|
||||
i -= 1;
|
||||
}
|
||||
(n1+n2, n)
|
||||
} else if n > 0 {
|
||||
// And these variables
|
||||
let mut n1:i64 = 0;
|
||||
let mut n2:i64 = 1;
|
||||
let mut i:i64 = 0;
|
||||
let mut tmp:i64;
|
||||
struct Fib<T> {
|
||||
curr: T,
|
||||
next: T,
|
||||
}
|
||||
|
||||
while i < n {
|
||||
f(n1);
|
||||
tmp = n1+n2;
|
||||
if tmp < 0 { //Detect overflow
|
||||
println!("\nReached the limit of i64, halting");
|
||||
return (n1, i);
|
||||
}
|
||||
n1 = n2;
|
||||
n2 = tmp;
|
||||
i += 1;
|
||||
}
|
||||
(n2-n1, n)
|
||||
} else {
|
||||
f(0);
|
||||
(0,1)
|
||||
impl<T> Fib<T> where T: One {
|
||||
fn new() -> Self {
|
||||
Fib {curr: T::one(), next: T::one()}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Iterator for Fib<T> where T: Add<T, Output=T> + Copy {
|
||||
type Item = T;
|
||||
fn next(&mut self) -> Option<Self::Item>{
|
||||
let new = self.curr + self.next;
|
||||
self.curr = self.next;
|
||||
self.next = new;
|
||||
Some(self.curr)
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let args = std::os::args();
|
||||
let default_n = 10i64;
|
||||
let n = match args.len() {
|
||||
1 => default_n,
|
||||
_ => args[1].parse().unwrap_or(default_n)
|
||||
};
|
||||
|
||||
/* Use the loop protocol to be able to do things
|
||||
* with the sequence given, in this case, print them out.
|
||||
* The loop itself returns a tuple with where it got to and
|
||||
* what the number is.
|
||||
*/
|
||||
let (result, n) = fib(n, |num| {
|
||||
//print out the sequence
|
||||
print!("{} ", num);
|
||||
});
|
||||
|
||||
println!("\nThe {}th fibonacci number is: {}", n, result);
|
||||
for i in Fib::<u64>::new() {
|
||||
println!("{}", i);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue