Slightly improve fibonacci and factorial examples

This commit is contained in:
Timothy Warren 2019-03-15 14:28:21 -04:00
parent 2f76f94476
commit 34b9a80e77
2 changed files with 11 additions and 17 deletions

View File

@ -12,18 +12,14 @@ use std::u128;
/// If the result overflows, an error message will be displayed.
fn factorial (n: usize, table: &mut Vec<u128>) -> Option<u128> {
match table.get(n) {
Some(x) => {
// Vec<T>.get returns a Option with a reference to the value, so deref
// Wrap in Some() for proper return type
Some(*x)
},
// Vec<T>.get returns a Option with a reference to the value,
// so deref and wrap in Some() for proper return type
Some(x) => Some(*x),
None => {
// If a previous base overflowed, just
// pass on the overflow. The overflow will
// be caught later. Using the max value of u128
// for convenience.
let prev = factorial(n - 1, table)
.unwrap_or(u128::MAX);
// The ? suffix passes along the Option value
// to be handled later
// See: https://doc.rust-lang.org/reference/expressions/operator-expr.html#the-question-mark-operator
let prev = factorial(n - 1, table)?;
// Do an overflow-checked multiply
let attempt = (n as u128).checked_mul(prev);

View File

@ -5,18 +5,16 @@ use separator::Separatable;
use std::io;
use std::u128;
///! Calculate a number in the fibonnacci sequence,
///! 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), // Vec<T>.get returns a Option with a reference to the value, so deref
Some(x) => Some(*x),
None => {
let a = fibonacci(n - 1, table)
.unwrap_or(u128::MAX);
let b = fibonacci(n - 2, table)
.unwrap_or(u128::MAX);
let a = fibonacci(n - 1, table)?;
let b = fibonacci(n - 2, table)?;
// Check for overflow when adding
let attempt = a.checked_add(b);