project-euler/156_counting_digits.py

34 lines
861 B
Python
Raw Normal View History

2023-03-25 17:24:17 +01:00
#!/usr/bin/env python3
def calc(n, dig=1, verbose=False):
r = 0
for place in range(len(str(n))):
a = (n - (n % 10**(place+1))) // 10
b = 0
d = int(str(n)[-place-1])
if d == dig:
b = (n % 10**place) + 1
elif d > dig:
b = 10**place
if verbose:
print(place, a, b, a+b)
r += a + b
return r
def search(dig, pw=2, num=0):
if pw == 0:
return sum(num + d for d in range(10) if num+d == calc(num+d, dig))
r = 0
for d in range(10):
newnum = num + d * 10**pw
maxnum = num + (d + 1) * 10**pw - 1
if maxnum < calc(newnum, dig):
continue
if calc(maxnum, dig) < newnum:
continue
r += search(dig, pw-1, newnum)
return r
depth = 10
print(sum(search(d, depth) for d in range(1, 10)))