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

View File

@ -5,18 +5,16 @@ use separator::Separatable;
use std::io; use std::io;
use std::u128; 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. ///! using a lookup table for better worst-case performance.
/// ///
/// Can calculate up to 186 using native unsigned 128 bit integers. /// Can calculate up to 186 using native unsigned 128 bit integers.
fn fibonacci(n: usize, table: &mut Vec<u128>) -> Option<u128> { fn fibonacci(n: usize, table: &mut Vec<u128>) -> Option<u128> {
match table.get(n) { 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 => { None => {
let a = fibonacci(n - 1, table) let a = fibonacci(n - 1, table)?;
.unwrap_or(u128::MAX); let b = fibonacci(n - 2, table)?;
let b = fibonacci(n - 2, table)
.unwrap_or(u128::MAX);
// Check for overflow when adding // Check for overflow when adding
let attempt = a.checked_add(b); let attempt = a.checked_add(b);