rust solutions problems 2 and 3

master
evan hemsley 2018-09-20 15:11:45 -07:00
parent 4c6bfa1821
commit 32ae71cf32
4 changed files with 111 additions and 0 deletions

View File

@ -1 +1,5 @@
pub mod prime;
pub mod problem_001;
pub mod problem_002;
pub mod problem_003;

53
rust/src/euler/prime.rs Normal file
View File

@ -0,0 +1,53 @@
fn subfactors(mut n: u64, p: u64) -> (u64, Vec<u64>) {
let mut subfactors = Vec::new();
let mut q = n / p;
let mut r = n % p;
while r == 0 {
subfactors.push(p);
n = q;
q = n / p;
r = n % p;
}
return (n, subfactors);
}
pub fn trial_factorization(mut n: u64) -> Vec<u64> {
let mut factors = Vec::new();
let (num, division_by_two) = subfactors(n, 2);
n = num; // is there a clean way to avoid this assignment?
factors.extend(division_by_two);
let (num, division_by_three) = subfactors(n, 3);
n = num;
factors.extend(division_by_three);
let mut p = 5;
while p * p <= n
{
let (num, division_by_p) = subfactors(n, p);
n = num;
factors.extend(division_by_p);
p += 2;
let (num, division_by_p_plus_two) = subfactors(n, p);
n = num;
factors.extend(division_by_p_plus_two);
p += 4;
}
if n >= 1 { factors.push(n); }
return factors;
}
#[cfg(test)]
mod tests {
use euler::prime::trial_factorization;
#[test]
fn test() {
assert_eq!(trial_factorization(20).len(), 3);
}
}

View File

@ -0,0 +1,39 @@
struct Fibonacci {
curr: u32,
next: u32,
}
impl Iterator for Fibonacci {
type Item = u32;
fn next(&mut self) -> Option<u32> {
let new = self.curr + self.next;
self.curr = self.next;
self.next = new;
Some(self.curr)
}
}
fn fibonacci() -> Fibonacci {
Fibonacci { curr: 1, next: 1 }
}
fn fibonacci_sum_up_to(number: u32) -> u32 {
return fibonacci().take_while(|n| n < &number).filter(|n| n % 2 == 0).sum();
}
fn solution() -> u32 {
return fibonacci_sum_up_to(4000000);
}
#[cfg(test)]
mod tests {
use euler::problem_002::solution;
#[test]
fn problem_002() {
assert_eq!(solution(), 4613732);
}
}

View File

@ -0,0 +1,15 @@
use euler::prime;
fn solution() -> Option<u64> {
return prime::trial_factorization(600851475143).last().cloned();
}
#[cfg(test)]
mod tests {
use euler::problem_003::solution;
#[test]
fn problem_003() {
assert_eq!(solution().unwrap(), 6857);
}
}