59 lines
1.2 KiB
Python
59 lines
1.2 KiB
Python
#!/usr/bin/env python3
|
|
|
|
from math import sqrt
|
|
|
|
def main(d):
|
|
mx = 0
|
|
my = 0
|
|
md = 0
|
|
for cd in range(2, d + 1):
|
|
x, y = diop(cd)
|
|
#print("{} -> {}, {}".format(cd, x, y))
|
|
if x > mx:
|
|
mx = x
|
|
my = y
|
|
md = cd
|
|
return md, mx, my
|
|
|
|
def diop(d):
|
|
sol = []
|
|
a, f = sq_frac(d)
|
|
f.reverse()
|
|
if len(f) == 0:
|
|
return 0, 0
|
|
for i in f:
|
|
for j in range(len(sol)):
|
|
sol[j][0], sol[j][1] = sol[j][0] * i + sol[j][1], sol[j][0]
|
|
sol.append([i, 1])
|
|
r = fits(a, sol, d)
|
|
while r == 0:
|
|
for i in f:
|
|
for j in range(len(sol)):
|
|
sol[j][0], sol[j][1] = sol[j][0] * i + sol[j][1], sol[j][0]
|
|
r = fits(a, sol, d)
|
|
return r
|
|
|
|
def fits(a, pairs, d):
|
|
for x, y in pairs[::-1]:
|
|
x, y = a * x + y, x
|
|
if x**2 - d * y**2 == 1:
|
|
return x, y
|
|
return 0
|
|
|
|
def sq_frac(x):
|
|
f = []
|
|
m = int(sqrt(x))
|
|
if m**2 == x:
|
|
return m, f
|
|
d = x - m**2
|
|
f.append((2 * m) // d)
|
|
n = f[-1] * d - m
|
|
while d != 1:
|
|
d = (x - n**2) // d
|
|
f.append((n + m) // d)
|
|
n = f[-1] * d - n
|
|
return m, f
|
|
|
|
if __name__ == '__main__':
|
|
print(main(1000)[0])
|