solution 5

master
Evan Hemsley 2019-10-06 22:43:22 -07:00
parent c1dfb112db
commit 727c36e795
4 changed files with 52 additions and 2 deletions

8
rust/src/euler/math.rs Normal file
View File

@ -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
}

View File

@ -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;
pub mod problem_005;

View File

@ -14,7 +14,8 @@ fn subfactors(mut n: u64, p: u64) -> (u64, Vec<u64>) {
(n, subfactors)
}
pub fn trial_factorization(mut n: u64) -> Vec<u64> {
pub fn trial_factorization(n: u64) -> Vec<u64> {
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<u64> {
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;

View File

@ -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);
}
}