solution 5
							parent
							
								
									c1dfb112db
								
							
						
					
					
						commit
						727c36e795
					
				|  | @ -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 | ||||
| } | ||||
|  | @ -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_004; | ||||
| pub mod problem_005; | ||||
|  | @ -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; | ||||
|  |  | |||
|  | @ -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); | ||||
|     } | ||||
| } | ||||
		Loading…
	
		Reference in New Issue