day2: fix arithmetic bruteforce algorithm & test

This commit is contained in:
2025-12-02 12:55:05 -08:00
parent 713cca6909
commit 8dd7831caa

View File

@@ -88,14 +88,22 @@ fn part2_arithmetic_brute(input: &[RangeInclusive<u64>]) -> u64 {
let n_digits = product.ilog10() + 1; let n_digits = product.ilog10() + 1;
for n in 1..=n_digits / 2 { for n in 1..=n_digits / 2 {
let repetitions = n_digits / n;
if n_digits % n != 0 { if n_digits % n != 0 {
continue; continue;
} }
let decade = 10u64.pow(n); let decade = 10u64.pow(n_digits - n);
let lhs = product / decade; let lhs = product / decade;
let rhs = product % decade; let remainder = product % decade;
if lhs == rhs {
invalid_sum += product // for each repetition we multiply by 10^(rep * n)
let expected_remainder = (0..repetitions - 1)
.map(|rep| lhs * 10u64.pow(rep * n))
.sum();
if remainder == expected_remainder {
invalid_sum += product;
break;
} }
} }
} }
@@ -155,7 +163,7 @@ mod tests {
} }
#[test] #[test]
fn part2_arithmetic_example() { fn part2_arithmetic_example() {
assert_eq!(part2_arithmetic_brute(&parse(EXAMPLE)), 1227775554); assert_eq!(part2_arithmetic_brute(&parse(EXAMPLE)), 4174379265);
} }
#[test] #[test]
fn part1_clever_example() { fn part1_clever_example() {