Optimized solution

This commit is contained in:
2026-06-21 20:32:51 +02:00
parent d78e9d6c63
commit 4681a782b5

View File

@@ -18,21 +18,30 @@
# an MD5 hash starting with five zeroes is 1048970; that is, the MD5 hash of
# pqrstuv1048970 looks like 000006136ef....
# Your puzzle input is yzbqklnj.
from hashlib import md5
from itertools import count
_input = "yzbqklnj"
with open("files/P4.txt") as f:
secret_key = f.read().strip()
key_bytes = secret_key.encode()
def part_1() -> None:
end = "9" * len(_input)
for num in range(int(end)):
testing = _input + str(num)
result = md5(testing.encode()).hexdigest()
if result.startswith("0" * 5):
print(f"The lowest positive number is {num}")
break
padding = 5
prefix = "0" * padding
base_hash = md5(key_bytes)
for num in count(1):
digest_ctx = base_hash.copy()
digest_ctx.update(str(num).encode())
digest = digest_ctx.hexdigest()
if digest.startswith(prefix):
print(f"The lowest positive number starting with {padding} zeroes is {num}")
return
raise RuntimeError("No valid number found")
# --- Part Two ---
@@ -41,13 +50,19 @@ def part_1() -> None:
def part_2() -> None:
end = "9" * len(_input)
for num in range(int(end)):
testing = _input + str(num)
result = md5(testing.encode()).hexdigest()
if result.startswith("0" * 6):
print(f"The lowest positive number is {num}")
break
padding = 6
prefix = "0" * padding
base_hash = md5(key_bytes)
for num in count(1):
digest_ctx = base_hash.copy()
digest_ctx.update(str(num).encode())
digest = digest_ctx.hexdigest()
if digest.startswith(prefix):
print(f"The lowest positive number starting with {padding} zeroes is {num}")
return
raise RuntimeError("No valid number found")
if __name__ == "__main__":