Solve some problems.
This commit is contained in:
81
python/e141.py
Normal file
81
python/e141.py
Normal file
@@ -0,0 +1,81 @@
|
||||
from math import isqrt, gcd
|
||||
|
||||
|
||||
def issqrt(n):
|
||||
isq = isqrt(n)
|
||||
return isq * isq == n
|
||||
|
||||
|
||||
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
|
||||
|
||||
with concurrent.futures.ProcessPoolExecutor() as executor:
|
||||
futures = []
|
||||
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
|
||||
|
||||
|
||||
def euler_141():
|
||||
r = 0
|
||||
NMAX = 10**12
|
||||
a = 1
|
||||
while True:
|
||||
if a**3 > NMAX:
|
||||
break
|
||||
for b in range(1, a):
|
||||
if a**3 * b**2 > NMAX:
|
||||
break
|
||||
|
||||
if gcd(a, b) != 1:
|
||||
continue
|
||||
|
||||
c = 1
|
||||
while True:
|
||||
n = a**3 * b * c**2 + c * b**2
|
||||
if n > NMAX:
|
||||
break
|
||||
if issqrt(n):
|
||||
# print(n)
|
||||
r += n
|
||||
c += 1
|
||||
a += 1
|
||||
return r
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
solution = euler_141()
|
||||
print("e141.py: " + str(solution))
|
||||
assert solution == 878454337159
|
||||
Reference in New Issue
Block a user