Diophantine equation
Problem 66
Consider quadratic Diophantine equations of the form:
x2 – Dy2 = 1
For example, when D=13, the minimal solution in x is 6492 – 13×1802 = 1.
It can be assumed that there are no solutions in positive integers when D is square.
By finding minimal solutions in x for D = {2, 3, 5, 6, 7}, we obtain the following:
32 – 2×22 = 1
22 – 3×12 = 1
92 – 5×42 = 1
52 – 6×22 = 1
82 – 7×32 = 1
22 – 3×12 = 1
92 – 5×42 = 1
52 – 6×22 = 1
82 – 7×32 = 1
Hence, by considering minimal solutions in x for D ≤ 7, the largest x is obtained when D=5.
Find the value of D ≤ 1000 in minimal solutions of x for which the largest value of x is obtained.
def count(n):
x, y = 1, int(n**0.5)
q, lastq = 1, 2 * y
while q != lastq:
q = int(x * (n**0.5 + y) / (n - y**2))
yield q
x, y = (n - y**2) // x, q * (n - y**2) // x - y
def run():
# https://www.mathblog.dk/project-euler-66-diophantine-equation/
maxd = 1000
dees = [i for i in range(2, maxd + 1) if int(i**0.5 + 0.5)**2 != i]
data = {}
for d in dees:
seq = [val for val in count(d)]
seq.insert(0, int(d**0.5))
if (len(seq) - 2) & 1:
seq.pop(-1)
else:
seq.extend(seq[1:-1])
den, num = 1, seq[-1]
for i in range(len(seq) - 2, -1, -1):
num, den = seq[i] * num + den, num # GCD always 1
data[num] = d # num = x, den = y
return data[max(data.iterkeys())]