day 04
the ideal stocking stuffer
approach
the secret key is read from stdin and nonces are tried in order, hashing key + nonce with md5 until the digest starts with enough zeros.
the check works on the raw digest bytes instead of the hex string: every two hex zeros are one zero byte, and an odd leftover zero means the next byte is below 0x10. part 1 asks for 5 zeros and part 2 for 6, with the same function.
the trick
count leading hex zeros on the raw bytes: whole zero bytes first, then a half byte.
python
def k_prefix_zeros(digest, k):
i = 0
while k >= 2:
if digest[i] != 0:
return False
k -= 2
i += 1
if k > 0:
return digest[i] < 0x10
return True