Solve problem 142 and make 141 brute force work again.

This commit is contained in:
2024-04-28 15:46:26 -04:00
parent e9873eaa2f
commit 0c1280ce91
2 changed files with 64 additions and 27 deletions

View File

@@ -1,3 +1,4 @@
import concurrent.futures
from math import isqrt, gcd
@@ -6,32 +7,32 @@ def issqrt(n):
return isq * isq == n
def have_same_ratio(a, b, c, d):
if b == 0 or d == 0:
raise ValueError("Denominators must be non-zero")
return a * d == b * c
def check_range(start, end):
local_sum = 0
for i in range(start, end):
if i % 10000 == 0:
print(i)
n = i * i
for d in range(1, i):
q = n // d
r = n % d
if r == 0:
continue
assert r < d and d < q
if have_same_ratio(d, r, q, d):
print(f"{n=} {i=} {r=} {d=} {q=}")
local_sum += n
break
return local_sum
def euler_141_brute_force():
import concurrent.futures
def have_same_ratio(a, b, c, d):
if b == 0 or d == 0:
raise ValueError("Denominators must be non-zero")
return a * d == b * c
def check_range(start, end):
local_sum = 0
for i in range(start, end):
if i % 10000 == 0:
print(i)
n = i * i
for d in range(1, i):
q = n // d
r = n % d
if r == 0:
continue
assert r < d and d < q
if have_same_ratio(d, r, q, d):
print(f"{n=} {i=} {r=} {d=} {q=}")
local_sum += n
break
return local_sum
s = 0
m = 1_000_000
range_size = 10_000
@@ -41,10 +42,8 @@ def euler_141_brute_force():
for start in range(1, m, range_size):
end = min(start + range_size, m)
futures.append(executor.submit(check_range, start, end))
for future in concurrent.futures.as_completed(futures):
s += future.result()
return s