Solve problem 142 and make 141 brute force work again.

main
felixm 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

38
python/e142.py Normal file
View File

@ -0,0 +1,38 @@
from math import isqrt
def iq(n):
isq = isqrt(n)
return isq * isq == n
def euler_142():
# x + y x - y x + z x - z y + z y - z
NMAX = 1_000_000
squares = [n * n for n in range(1, NMAX)]
for x in range(1, NMAX):
for s1 in squares:
y = x - s1 # s1 = x - y
if y <= 0:
break
if not iq(x + y): # s2 = x + y
continue
for s3 in squares:
z = y - s3 # s3 = y - z
if x - z <= 0:
continue
if z <= 0:
break
if not iq(y + z): # s4 = y + z
continue
if iq(x + z) and iq(x - z):
print(x, y, z, x + y + z)
return x + y + z
return None
if __name__ == "__main__":
solution = euler_142()
print("e142.py: " + str(solution))
assert solution == 1006193