hhoppe

Advent of code 2025 day 2 super-fast

Dec 8th, 2025
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.00 KB | None | 0 0
  1. # Arithmetic solution.  E.g., a 6-digit value divisible by 111111, 10101, or 1001 consists of
  2. # a repeated digit sequence (of length 1, 2, or 3).  We iterate over the in-range multiples.
  3.  
  4. def day2(s, *, part2=False):
  5.  
  6.   def split_by_num_digits(start, stop):
  7.     """Partition an integer range into subranges with the same number of digits."""
  8.     while start < stop:
  9.       end = min(10 ** (math.floor(math.log10(start)) + 1), stop)
  10.       yield start, end
  11.       start = end
  12.  
  13.   total = 0
  14.   for lo, hi in re.findall(r'(\d+)-(\d+)', s):
  15.     for start, stop in split_by_num_digits(int(lo), int(hi) + 1):
  16.       num_digits = math.floor(math.log10(start)) + 1
  17.       divisors = [
  18.           (10**num_digits - 1) // (10**p - 1)
  19.           for p in range(1, num_digits)
  20.           if num_digits % p == 0 and (p * 2 == num_digits or part2)
  21.       ]
  22.       values = set()
  23.       for d in divisors:
  24.         values.update(range(-(-start // d) * d, (stop - 1) // d * d + 1, d))
  25.       total += sum(values)
  26.  
  27.   return total
Advertisement
Add Comment
Please, Sign In to add comment