Skip to content

Commit

Permalink
math: Tuning fib(), remove cache vector
Browse files Browse the repository at this point in the history
  • Loading branch information
XuShaohua committed Jul 24, 2023
1 parent 8af851c commit 8d0782d
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 19 deletions.
4 changes: 2 additions & 2 deletions math/benches/fibonacci.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
// Use of this source is governed by General Public License that can be found
// in the LICENSE file.

use criterion::{criterion_group, criterion_main, Criterion};
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use math::fibonacci::fib;

pub fn fib_bench(c: &mut Criterion) {
c.bench_function("fib 80", |b| b.iter(|| fib(80)));
c.bench_function("math::fib-80", |b| b.iter(|| fib(black_box(80))));
}

criterion_group!(benches, fib_bench);
Expand Down
30 changes: 13 additions & 17 deletions math/src/fibonacci.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,24 +18,20 @@ pub const MAX_INDEX: u8 = 93;
/// # Errors
/// Returns error if `num` is not a possitive integer.
pub fn fib(num: u8) -> Result<u64, FibError> {
if num > MAX_INDEX {
return Err(FibError::IllegalIndex);
let mut a = 0;
let mut b = 1;
match num {
0 => Ok(0),
num if num > MAX_INDEX => Err(FibError::IllegalIndex),
_ => {
for _ in 1..num {
let c = a + b;
a = b;
b = c;
}
Ok(b)
}
}
if num == 0 {
return Ok(0);
}
if num == 1 {
return Ok(1);
}

let num = num as usize;
let mut buf: Vec<u64> = vec![0; num + 1];
buf[0] = 0;
buf[1] = 1;
for i in 2..=num {
buf[i] = buf[i - 1] + buf[i - 2];
}
Ok(buf[num])
}

#[cfg(test)]
Expand Down

0 comments on commit 8d0782d

Please sign in to comment.