To find the period of a continued fraction, specifically to solve problem Project Euler #64
I did the following.
ProjectEuler+Project Euler #64: Odd period square roots
ProjectEuler.net #64: Odd period square roots
Start With:
$ \sqrt{n} = \lfloor \sqrt{n} \rfloor + \sqrt{n} - \lfloor \sqrt{n} \rfloor $
$ \text{Got }x_1 = \lfloor \sqrt{n} \rfloor $
$ \sqrt{n} = x_1 + \sqrt{n} - x_1 = x_1 + \frac{1}{\frac{1}{\sqrt{n} - x_1}}$
So:
$a_0 = (a_0^{int},a_0^{frac})= x_1, {\frac{1}{\sqrt{n} - x_1}} ⇒ a_0^{frac} = {\frac{\sqrt{n} + x_1}{n - x_1^2}}$
For recursion purposes.
$ (k = 1 \space , \space den = n - x_1^2) ⇒ a_0^{frac} = \frac{k(\sqrt{n} + x_1)}{den} $
First iteration:
$ a_1^{int} =\left \lfloor {a_0^{frac}} \right \rfloor =
\left \lfloor \frac{k(\sqrt{n} + x_1)}{den} \right \rfloor = c $
$ finv(a_1^{frac}) = \frac{k(\sqrt{n} + x_1)}{den} - c =
\frac{(k\sqrt{n} + k \cdot x_1 - c \cdot den)}{den} =
\frac{k(\sqrt{n} - (\frac{c \cdot den}{k} - x_1 ))}{den} ⇒\\
a_1^{frac} = \frac{\frac{den}{k}}{(\sqrt{n} - (\frac{c \cdot den}{k} - x_1 ))} ⇒ \text{New values} \space ⇒ (k_2 = \frac{den}{k},x_2 = \frac{c \cdot den}{k} - x_1, den_2 = n - x_2^2)$
The recursion continues until $ a_n^{frac} = a_0^{frac}$ when the period starts and the fractional part values repeat infinitely.
In this idea, I elaborated the following algorithm:
https://github.com/rafaeldjsm/Matematica/blob/main/ProjectEuler_64__square_roots.ipynb
from math import sqrt
def perfarc(n):
root = int(sqrt(n))
if root == sqrt(n):
return 0
a = 1
listaint = [root]
den = n - root2
lista_inv_frac = [(sqrt(n)+root)/den]
per = 0
while True:
part_int = int(lista_inv_frac[-1])
root = (den * part_int)/a - root
a = den/a
den = (n-root2)
invfrac = a*(sqrt(n)+root)/den
listaint.append(part_int)
lista_inv_frac.append(invfrac)
per+=1
if invfrac == lista_inv_frac[0]:
return per
n = int(input())
cntodd = 0
for k in range(2,n+1):
if perfarc(k)%2 == 1:
cntodd+=1
cntodd