Project Euler #66: Diophantine equation
Difficulty: Hard

<sub>This problem is a programming version of [Problem 66](https://projecteuler.net/problem=66) from [projecteuler.net](https://projecteuler.net/)</sub>  

Consider quadratic Diophantine equations of the form:

$$x^2 - Dy^2 = 1$$

For example, when $D=13$, the minimal solution in $x$ is $649^2 - 13×180^2 = 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:  

$$3^2 - 2\times2^2 = 1 \\\
 2^2 - 3 \times 1^2 = 1 \\\
 \textbf{9}^2 - 5 \times 4^2 = 1 \\\
 5^2 - 6 \times 2^2 = 1 \\\
 8^2 - 7 \times 3^2 = 1 \\\
 $$

Hence, by considering minimal solutions in $x$ for $D \le 7$, the largest $x$ is obtained when $D=5$.  

Find the value of $D \le N$ in minimal solutions of $x$ for which the largest value of $x$ is obtained.  


Input Format:
Input contains an integer $N$.  

**Constraints**  
$7 \le N \le 10^4$

Output Format:
Print the answer corresponding to the test case.

Sample Input:
```raw
7
```

Sample Output:
```raw
5
```

Python 3 starter code:


Reference solution (Python):
```python
import math


def gen(n):
    n2 = int(math.sqrt(n))
    num = 1
    den = n2
    yield n2
    while True:
        x = num
        num = den
        den = (n - den * den) / x
        p = int(n2 + 0.5 + num) / den
        yield p
        num = p * den - num
        num, den = den, num


def solve_x(d):
    h0, h1 = 0, 1
    k0, k1 = 1, 0
    g = gen(d)
    for a in g:
        h0, h1 = h1, a*h1+h0
        k0, k1 = k1, a*k1+k0
        # print h1, k1, h1*h1 - d*k1*k1
        if h1*h1 - d*k1*k1 == 1:
            return h1


N = int(raw_input())
sq = 1
best_x, best_d = 0, 0
for d in xrange(1, N+1):
    while sq*sq < d: sq += 1
    if sq*sq == d: continue
    act_x = solve_x(d)
    if act_x > best_x:
        best_x = act_x
        best_d = d
print best_d
```