From 727c36e795adc6f2dbbad75febc26b765be444bd Mon Sep 17 00:00:00 2001 From: Evan Hemsley Date: Sun, 6 Oct 2019 22:43:22 -0700 Subject: [PATCH] solution 5 --- rust/src/euler/math.rs | 8 ++++++++ rust/src/euler/mod.rs | 4 +++- rust/src/euler/prime.rs | 21 ++++++++++++++++++++- rust/src/euler/problem_005.rs | 21 +++++++++++++++++++++ 4 files changed, 52 insertions(+), 2 deletions(-) create mode 100644 rust/src/euler/math.rs create mode 100644 rust/src/euler/problem_005.rs diff --git a/rust/src/euler/math.rs b/rust/src/euler/math.rs new file mode 100644 index 0000000..c012e7d --- /dev/null +++ b/rust/src/euler/math.rs @@ -0,0 +1,8 @@ +pub fn gcd(mut a: u64, mut b: u64) -> u64 { + while b != 0 { + let t = a; + a = b; + b = t % b; + } + a +} \ No newline at end of file diff --git a/rust/src/euler/mod.rs b/rust/src/euler/mod.rs index 1dd8e64..7282160 100644 --- a/rust/src/euler/mod.rs +++ b/rust/src/euler/mod.rs @@ -1,6 +1,8 @@ pub mod prime; +pub mod math; pub mod problem_001; pub mod problem_002; pub mod problem_003; -pub mod problem_004; \ No newline at end of file +pub mod problem_004; +pub mod problem_005; \ No newline at end of file diff --git a/rust/src/euler/prime.rs b/rust/src/euler/prime.rs index c5f41a2..fd867de 100644 --- a/rust/src/euler/prime.rs +++ b/rust/src/euler/prime.rs @@ -14,7 +14,8 @@ fn subfactors(mut n: u64, p: u64) -> (u64, Vec) { (n, subfactors) } -pub fn trial_factorization(mut n: u64) -> Vec { +pub fn trial_factorization(n: u64) -> Vec { + let mut n = n; let mut factors = Vec::new(); let (num, division_by_two) = subfactors(n, 2); @@ -42,6 +43,24 @@ pub fn trial_factorization(mut n: u64) -> Vec { factors } +fn root(n: u64, f: u64) -> u64 { + let mut n = n; + let mut result = 0; + + while n % f == 0 { + result += 1; + n /= f; + } + + result +} + +pub fn prime_factorization(n: u64) -> Vec<(u64, u64)> { + let factors = trial_factorization(n); + let exponents = factors.iter().map( |&f| root(n, f) ); + factors.iter().zip(exponents).map( |(&i, j)| (i, j) ).collect() +} + #[cfg(test)] mod tests { use euler::prime::trial_factorization; diff --git a/rust/src/euler/problem_005.rs b/rust/src/euler/problem_005.rs new file mode 100644 index 0000000..fece3a3 --- /dev/null +++ b/rust/src/euler/problem_005.rs @@ -0,0 +1,21 @@ +use euler::math; + +fn smallest_divisible_by_all_up_to(n: u64) -> u64 { + (2..n).fold(1, |acc, i| { + acc * i / math::gcd(i, acc) + }) +} + +pub fn solution() -> u64 { + smallest_divisible_by_all_up_to(20) +} + +#[cfg(test)] +mod tests { + use euler::problem_005::solution; + + #[test] + fn problem_005() { + assert_eq!(solution(), 232_792_560); + } +} \ No newline at end of file