Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Arithmetic solution. E.g., a 6-digit value divisible by 111111, 10101, or 1001 consists of
- # a repeated digit sequence (of length 1, 2, or 3). We iterate over the in-range multiples.
- def day2(s, *, part2=False):
- def split_by_num_digits(start, stop):
- """Partition an integer range into subranges with the same number of digits."""
- while start < stop:
- end = min(10 ** (math.floor(math.log10(start)) + 1), stop)
- yield start, end
- start = end
- total = 0
- for lo, hi in re.findall(r'(\d+)-(\d+)', s):
- for start, stop in split_by_num_digits(int(lo), int(hi) + 1):
- num_digits = math.floor(math.log10(start)) + 1
- divisors = [
- (10**num_digits - 1) // (10**p - 1)
- for p in range(1, num_digits)
- if num_digits % p == 0 and (p * 2 == num_digits or part2)
- ]
- values = set()
- for d in divisors:
- values.update(range(-(-start // d) * d, (stop - 1) // d * d + 1, d))
- total += sum(values)
- return total
Advertisement
Add Comment
Please, Sign In to add comment