project-euler/162_hexadecimal_numbers.py

31 lines
743 B
Python

#!/usr/bin/env python3
from itertools import product
from math import factorial
def bin(n, k):
return factorial(n) // (factorial(n-k) * factorial(k))
digs = list(map(str, range(10))) + list("ABCDEF")
cache = {val : {0 : all(val)} for val in product([True, False], repeat=3)}
def f(i, flags=(False, False, False), fst=1):
if i in cache[flags] and (not fst or not i):
return cache[flags][i]
r = 13 * f(i-1, flags, 0)
r += sum(f(i-1, flags[:n] + (True,) + flags[n+1:], 0) for n in range(fst, 3))
if not fst:
cache[flags][i] = r
return r
def dec2hex(n):
r = str()
while n:
r = r + digs[n % 16]
n //= 16
return r[::-1]
r = sum(f(i) for i in range(1, 17))
print(dec2hex(r))