From 34a1184e07f4a0696c365071ce6d7c590691d171 Mon Sep 17 00:00:00 2001 From: Olivia Appleton Date: Tue, 23 Jul 2024 01:35:31 -0500 Subject: [PATCH] Now that it compiles, narrow types further --- docs/rust/math.rst | 2 +- rust/src/math.rs | 23 +++++++++-------------- rust/src/p0034.rs | 8 +++----- 3 files changed, 13 insertions(+), 20 deletions(-) diff --git a/docs/rust/math.rst b/docs/rust/math.rst index 0d867b94..a1f989c7 100644 --- a/docs/rust/math.rst +++ b/docs/rust/math.rst @@ -8,7 +8,7 @@ View source code `here on GitHub! + NumAssign + PartialOrd>(n: u64, r: u64) -> I +.. rust:fn:: n_choose_r + NumAssign + PartialOrd>(n: usize, r: usize) -> I Returns the number of ways to choose r items from a set of n. diff --git a/rust/src/math.rs b/rust/src/math.rs index cf68140a..5edd8248 100644 --- a/rust/src/math.rs +++ b/rust/src/math.rs @@ -11,26 +11,24 @@ pub fn factorial>(n: u8) -> I { return answer } -pub fn n_choose_r + NumAssign + PartialOrd>(n: u64, r: u64) -> I { +pub fn n_choose_r + NumAssign + PartialOrd>(n: usize, r: usize) -> I { // slow path for larger numbers let mut answer: I = one(); - let sn: usize = n.try_into().unwrap(); - let sr: usize = r.try_into().unwrap(); let mut tmp: I; - let mut factors: Vec = vec![0; (n + 1).try_into().unwrap()]; + let mut factors: Vec = vec![0; n + 1]; // collect factors of final number - for i in 2..=sn { + for i in 2..=n { factors[i] = 1; } // negative factor values indicate need to divide - for i in 2..=sr { + for i in 2..=r { factors[i] -= 1; } - for i in 2..=(sn - sr) { + for i in 2..=(n - r) { factors[i] -= 1; } // this loop reduces to prime factors only - for i in (1..sn).rev() { + for i in (1..n).rev() { for j in 2..i { if i % j == 0 { factors[j] += factors[i]; @@ -42,11 +40,11 @@ pub fn n_choose_r + NumAssign + PartialOrd>(n: u64, r: u64) } let mut i: usize = 2; let mut j: usize = 2; - while i <= sn { + while i <= n { while factors[i] > 0 { tmp = answer; answer *= (i as u64).into(); - while answer < tmp && j <= sn { + while answer < tmp && j <= n { while factors[j] < 0 { tmp /= (j as u64).into(); factors[j] += 1; @@ -54,14 +52,11 @@ pub fn n_choose_r + NumAssign + PartialOrd>(n: u64, r: u64) j += 1; answer = tmp * (i as u64).into(); } - if answer < tmp { - panic!(); // overflow - } factors[i] -= 1; } i += 1; } - while j <= sn { + while j <= n { while factors[j] < 0 { answer /= (j as u64).into(); factors[j] += 1; diff --git a/rust/src/p0034.rs b/rust/src/p0034.rs index 7ddee979..be26df94 100644 --- a/rust/src/p0034.rs +++ b/rust/src/p0034.rs @@ -19,11 +19,9 @@ use crate::math::factorial; pub fn p0034() -> i128 { let mut answer: u32 = 0; for x in 10..100000 { - let string: String = x.to_string(); - let sum = - string.bytes() - .into_iter() - .fold(0, |a, b| a + factorial::(b - '0' as u8)); + let sum = x.to_string() + .bytes() + .fold(0, |a, b| a + factorial::(b - '0'.into())); if sum == x { answer += x; }