Pell's equation: Difference between revisions
Content added Content deleted
(Added Wren) |
(→{{header|Python}}: It's far more Pythonic to use multiple assignment than a helper method which uses arrays for pass-by-reference) |
||
Line 876: | Line 876: | ||
<lang python>import math |
<lang python>import math |
||
def |
def solvePell(n): |
||
t = a[0] |
|||
a[0] = b[0] |
|||
b[0] = b[0] * c + t |
|||
def solvePell(n, a, b): |
|||
x = int(math.sqrt(n)) |
x = int(math.sqrt(n)) |
||
y = x |
y, z, r = x, 1, x << 1 |
||
e1, e2 = 1, 0 |
|||
f1, f2 = 0, 1 |
|||
e1 = [1] |
|||
e2 = [0] |
|||
f1 = [0] |
|||
f2 = [1] |
|||
while True: |
while True: |
||
y = r * z - y |
y = r * z - y |
||
z = |
z = (n - y * y) // z |
||
r = (x + y) // z |
r = (x + y) // z |
||
⚫ | |||
⚫ | |||
⚫ | |||
b[0] = e2[0] |
|||
⚫ | |||
⚫ | |||
return |
|||
⚫ | |||
x = [0] |
|||
⚫ | |||
y = [0] |
|||
⚫ | |||
⚫ | |||
⚫ | |||
for n in [61, 109, 181, 277]: |
for n in [61, 109, 181, 277]: |
||
x, y = solvePell(n) |
|||
print("x^2 - %3d * y^2 = 1 for x = %27d and y = %25d" % (n, x |
print("x^2 - %3d * y^2 = 1 for x = %27d and y = %25d" % (n, x, y))</lang> |
||
{{out}} |
{{out}} |
||
<pre>x^2 - 61 * y^2 = 1 for x = 1766319049 and y = 226153980 |
<pre>x^2 - 61 * y^2 = 1 for x = 1766319049 and y = 226153980 |