@@ -678,22 +678,22 @@ One can further prove (and it was first done by Lagrange) that for arbitrary qua
678
678
```py
679
679
# compute the continued fraction of sqrt(n)
680
680
def sqrt(n):
681
- n0 = math.floor(math.sqrt(n))
682
- x, y, z = 1, 0, 1
683
- a = []
684
- def step(x, y, z):
685
- a.append((x * n0 + y) // z)
686
- t = y - a[-1]*z
687
- x, y, z = -z*x, z*t, t**2 - n*x**2
688
- g = math.gcd(x, math.gcd(y, z))
689
- return x // g, y // g, z // g
690
-
691
- used = dict()
692
- for i in range(n):
693
- used[x, y, z] = i
694
- x, y, z = step(x, y, z)
695
- if (x, y, z) in used:
696
- return a
681
+ n0 = math.floor(math.sqrt(n))
682
+ x, y, z = 1, 0, 1
683
+ a = []
684
+ def step(x, y, z):
685
+ a.append((x * n0 + y) // z)
686
+ t = y - a[-1]*z
687
+ x, y, z = -z*x, z*t, t**2 - n*x**2
688
+ g = math.gcd(x, math.gcd(y, z))
689
+ return x // g, y // g, z // g
690
+
691
+ used = dict()
692
+ for i in range(n):
693
+ used[x, y, z] = i
694
+ x, y, z = step(x, y, z)
695
+ if (x, y, z) in used:
696
+ return a
697
697
```
698
698
699
699
Using the same `step` function but different initial $x$, $y$ and $z$ it is possible to compute it for arbitrary $\frac{x+y \sqrt{n}}{z}$.
0 commit comments