Project Euler 66
Project Euler 66
题目
Diophantine equation
Consider quadratic Diophantine equations of the form:
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:
Hence, by considering minimal solutions in $x$ for $D \leq 7$, the largest $x$ is obtained when $D=5$.
Find the value of $D \leq 1000$ in minimal solutions of $x$ for which the largest value of $x$ is obtained.
解决方案
mathworld wolfram上介绍的关于佩尔方程$x^2-Dy^2=1$的一组特解的解法基于连分数解决(此处假设$D$为非平方整数)。
设$\sqrt{N}$产生的连分数序列表示成$[a_0;(a_1,a_2,\dots,a_n)]$,其中$a_n=2a_0$。
那么计算$\sqrt{N}$的连分数序列算法已在64题中的提到的维基百科页面给出:
$\begin{aligned}
m0 &=0 \
d_0 &= 1 \
a_0&=\lfloor\sqrt {S}\rfloor \
m{n+1}&=dna_n-m_n \
d{n+1}&=\dfrac{S-m{n+1}^2}{d_n}\
a{n+1}&=\left\lfloor\dfrac{a0+m{n+1}}{d_{n+1}}\right\rfloor
\end{aligned}$
网站上提到,为计算$x^2-Dy^2=1$,假设$\sqrt{N}$产生的第$m$个连分数$[a_0,a_1,\dots,a_m]$的分数形式为$\dfrac{p_m}{q_m}$。
那么如果连分数周期$n$为偶数,$x^2-Dy^2=1$的最小特解为$(p{n-1},q{n-1})$。
否则,$x^2-Dy^2=1$的最小特解为$(p{2n-1},q{2n-1})$。
直接使用这一些结论进行计算。
另外,假设该最小特解为$(x_1,y_1)$,那么佩尔方程的通解$(x_k,y_k)$可以由以下结果导出:
即有关于$(x_k,y_k)$两个序列的递推式:
代码
1 | from fractions import Fraction |