-
-
Notifications
You must be signed in to change notification settings - Fork 51k
Expand file tree
/
Copy pathsol1.py
More file actions
107 lines (88 loc) · 3.78 KB
/
Copy pathsol1.py
File metadata and controls
107 lines (88 loc) · 3.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
"""
Project Euler Problem 092: https://projecteuler.net/problem=92
Square digit chains
A number chain is created by continuously adding the square of the digits in
a number to form a new number until it has been seen before.
For example,
44 → 32 → 13 → 10 → 1 → 1
85 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89
Therefore any chain that arrives at 1 or 89 will become stuck in an endless loop.
What is most amazing is that EVERY starting number will eventually arrive at 1 or 89.
How many starting numbers below ten million will arrive at 89?
References:
- https://en.wikipedia.org/wiki/Digital_root
- https://en.wikipedia.org/wiki/Digit_DP
"""
def solution(number: int = 10_000_000) -> int:
"""
Returns how many starting numbers below `number` will arrive at 89
in the digit-square chain.
Uses digit DP so the count is computed in O(k * d_max * 10) time —
roughly 40 000 operations for number = 10^7 — instead of iterating
all `number` values explicitly.
Key observations:
1. For any n < number, digit_square_sum(n) ≤ num_digits * 81,
so chain endpoints can be precomputed for that small range only.
2. A digit DP over the decimal digits of (number - 1) counts how many
integers in [0, number-1] have each possible digit-square sum,
grouping by whether the prefix is still bounded ("tight") or free.
Integers whose digit-square sum equals 0 are exactly 0 itself.
>>> solution(100)
80
>>> solution(10_000_000)
8581146
"""
num_digits = len(str(number - 1)) if number > 1 else 1
limit = num_digits * 81 + 1 # max possible digit-square sum + 1
def digit_square_sum(n: int) -> int:
total = 0
while n:
total += (n % 10) ** 2
n //= 10
return total
# Precompute whether each value 1..limit-1 eventually reaches 89.
# All intermediate chain values stay below limit because the digit-square
# sum of any k-digit number is at most k * 81 = limit - 1.
ends_at_89 = bytearray(limit)
for i in range(1, limit):
n = i
while n not in (1, 89):
n = digit_square_sum(n)
ends_at_89[i] = n == 89
# Digit DP over the decimal digits of (number - 1).
# Treating shorter numbers as zero-padded strings (e.g. 7 → "0000007")
# is safe because 0^2 = 0 contributes nothing to the digit-square sum.
# dp_tight[s] / dp_free[s] = count of digit sequences whose running
# digit-square sum is s and whose prefix is still ≤ / already < the
# corresponding prefix of (number - 1).
digits = [int(d) for d in str(number - 1)] if number > 1 else [0]
dp_tight: dict[int, int] = {0: 1}
dp_free: dict[int, int] = {}
for lim in digits:
new_tight: dict[int, int] = {}
new_free: dict[int, int] = {}
for dss, cnt in dp_tight.items():
for d in range(lim + 1):
new_val = dss + d * d
if new_val < limit:
if d == lim:
new_tight[new_val] = new_tight.get(new_val, 0) + cnt
else:
new_free[new_val] = new_free.get(new_val, 0) + cnt
for dss, cnt in dp_free.items():
for d in range(10):
new_val = dss + d * d
if new_val < limit:
new_free[new_val] = new_free.get(new_val, 0) + cnt
dp_tight, dp_free = new_tight, new_free
# Sum counts for all digit-square sums that end at 89.
# dss == 0 corresponds to the number 0, which is excluded.
return sum(
cnt
for dss, cnt in (*dp_tight.items(), *dp_free.items())
if 0 < dss < limit and ends_at_89[dss]
)
if __name__ == "__main__":
import doctest
doctest.testmod()
print(f"{solution() = }")