Optimize problem 1
This commit is contained in:
parent
567a649c7d
commit
f978ffbfa1
1 changed files with 15 additions and 2 deletions
17
src/one.rs
17
src/one.rs
|
|
@ -6,12 +6,25 @@ pub struct Args {
|
||||||
pub until: u64,
|
pub until: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn multiple_sum_until(m: u64, n: u64) -> u64 {
|
||||||
|
let k = n / m;
|
||||||
|
m * k * (k + 1) / 2
|
||||||
|
}
|
||||||
|
|
||||||
impl Problem for Args {
|
impl Problem for Args {
|
||||||
type Solution = u64;
|
type Solution = u64;
|
||||||
|
|
||||||
// We could derive it mathematically, ... or write a dump loop
|
// Multiple of threes:
|
||||||
|
// 3 6 9 12 ... = 3 * 1 + 3 * 2 + 3 * 3 ... = 3 * (1 + 2 + 3 ...)
|
||||||
|
// Identically multiples of 5: 5 * (1 + 2 + 3 ...)
|
||||||
|
//
|
||||||
|
// We need all multiples such that 3 * n < X, n < X / 3
|
||||||
fn solve(self, _: GlobalArgs) -> color_eyre::Result<u64> {
|
fn solve(self, _: GlobalArgs) -> color_eyre::Result<u64> {
|
||||||
let sum = (0..self.until).filter(|x| x % 3 == 0 || x % 5 == 0).sum();
|
let three_sum = multiple_sum_until(3, self.until - 1);
|
||||||
|
let five_sum = multiple_sum_until(5, self.until - 1);
|
||||||
|
let fifteen_sum = multiple_sum_until(15, self.until - 1);
|
||||||
|
|
||||||
|
let sum = three_sum + five_sum - fifteen_sum;
|
||||||
|
|
||||||
Ok(sum)
|
Ok(sum)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue