Odd Period Square Roots
All square roots are periodic when written as continued fractions and can be written in the form:
For example, let us consider
If we continue we would get the following expansion:
The process can be summarised as follows:
\begin{align} \quad \quad a_0 &= 4, \frac 1 {\sqrt{23}-4}=\frac {\sqrt{23}+4} 7=1+\frac {\sqrt{23}-3} 7 \\ \quad \quad a_1 &= 1, \frac 7 {\sqrt{23}-3}=\frac {7(\sqrt{23}+3)} {14}=3+\frac {\sqrt{23}-3} 2 \\ \quad \quad a_2 &= 3, \frac 2 {\sqrt{23}-3}=\frac {2(\sqrt{23}+3)} {14}=1+\frac {\sqrt{23}-4} 7 \\ \quad \quad a_3 &= 1, \frac 7 {\sqrt{23}-4}=\frac {7(\sqrt{23}+4)} 7=8+\sqrt{23}-4 \\ \quad \quad a_4 &= 8, \frac 1 {\sqrt{23}-4}=\frac {\sqrt{23}+4} 7=1+\frac {\sqrt{23}-3} 7 \\ \quad \quad a_5 &= 1, \frac 7 {\sqrt{23}-3}=\frac {7 (\sqrt{23}+3)} {14}=3+\frac {\sqrt{23}-3} 2 \\ \quad \quad a_6 &= 3, \frac 2 {\sqrt{23}-3}=\frac {2(\sqrt{23}+3)} {14}=1+\frac {\sqrt{23}-4} 7 \\ \quad \quad a_7 &= 1, \frac 7 {\sqrt{23}-4}=\frac {7(\sqrt{23}+4)} {7}=8+\sqrt{23}-4 \end{align}
It can be seen that the sequence is repeating. For conciseness, we use the notation , to indicate that the block (1,3,1,8) repeats indefinitely.
The first ten continued fraction representations of (irrational) square roots are:
, period=
, period=
, period=
, period=
, period=
, period=
, period=
, period=
, period=
, period=
Exactly four continued fractions, for , have an odd period.
How many continued fractions for have an odd period?
Implementations
#include <iostream>#include <vector>#include <cmath>#include <map>#include <tuple>
int odd_period_square_roots() { int count = 0; for (long long N = 2; N <= 10000; ++N) { long long sqrtN = (long long)std::sqrt(N); if (sqrtN * sqrtN == N) continue; long long m = 0; long long d = 1; long long a = sqrtN; long long period = 0; long long a0 = sqrtN; long long an = sqrtN; while (an != 2 * a0) { m = d * an - m; d = (N - m * m) / d; an = (a0 + m) / d; period++; } if (period % 2 == 1) ++count; } return count;}
#if ! defined UNITTEST_MODEint main(int argc, char const *argv[]) { std::cout << odd_period_square_roots() << std::endl;}#endif // UNITTEST_MODE