Pell's equation: Difference between revisions

(→‎{{header|Haskell}}: added solution)
(24 intermediate revisions by 16 users not shown)
Line 15:
:* &nbsp; Wikipedia entry: [https://en.wikipedia.org/wiki/Pell%27s_equation <u>Pell's equation</u>].
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F solvePell(n)
V x = Int(sqrt(n))
V (y, z, r) = (x, 1, x << 1)
BigInt e1 = 1
BigInt e2 = 0
BigInt f1 = 0
BigInt f2 = 1
L
y = r * z - y
z = (n - y * y) I/ z
r = (x + y) I/ z
 
(e1, e2) = (e2, e1 + e2 * r)
(f1, f2) = (f2, f1 + f2 * r)
 
V (a, b) = (f2 * x + e2, f2)
I a * a - n * b * b == 1
R (a, b)
 
L(n) [61, 109, 181, 277]
V (x, y) = solvePell(n)
print(‘x^2 - #3 * y^2 = 1 for x = #27 and y = #25’.format(n, x, y))</syntaxhighlight>
 
{{out}}
<pre>
x^2 - 61 * y^2 = 1 for x = 1766319049 and y = 226153980
x^2 - 109 * y^2 = 1 for x = 158070671986249 and y = 15140424455100
x^2 - 181 * y^2 = 1 for x = 2469645423824185801 and y = 183567298683461940
x^2 - 277 * y^2 = 1 for x = 159150073798980475849 and y = 9562401173878027020
</pre>
 
=={{header|Ada}}==
{{Trans|C}}{{works with|Ada 2022}}
<syntaxhighlight lang="ada">with Ada.Text_Io;
with Ada.Numerics.Elementary_Functions;
with Ada.Numerics.Big_Numbers.Big_Integers;
 
procedure Pells_Equation is
use Ada.Numerics.Big_Numbers.Big_Integers;
 
type Pair is
record
V1, V2 : Big_Integer;
end record;
 
procedure Solve_Pell (N : Natural; X, Y : out Big_Integer) is
use Ada.Numerics.Elementary_Functions;
Big_N : constant Big_Integer := To_Big_Integer (N);
XX : constant Big_Integer := To_Big_Integer (Natural (Float'Floor (Sqrt (Float (N)))));
begin
if XX**2 = Big_N then
X := 1; Y := 0;
return;
end if;
 
declare
YY : Big_Integer := XX;
Z : Big_Integer := 1;
R : Big_Integer := 2 * XX;
E : Pair := Pair'(V1 => 1, V2 => 0);
F : Pair := Pair'(V1 => 0, V2 => 1);
begin
loop
YY := R * Z - YY;
Z := (Big_N - YY**2) / Z;
R := (XX + YY) / Z;
E := Pair'(V1 => E.V2, V2 => R * E.V2 + E.V1);
F := Pair'(V1 => F.V2, V2 => R * F.V2 + F.V1);
X := E.V2 + XX * F.V2;
Y := F.V2;
exit when X**2 - Big_N * Y**2 = 1;
end loop;
end;
end Solve_Pell;
 
procedure Test (N : Natural) is
 
package Natural_Io is new Ada.Text_Io.Integer_Io (Natural);
use Ada.Text_Io, Natural_Io;
 
X, Y : Big_Integer;
begin
Solve_Pell (N, X => X, Y => Y);
Put ("X**2 - ");
Put (N, Width => 3);
Put (" * Y**2 = 1 for X = ");
Put (To_String (X, Width => 22));
Put (" and Y = ");
Put (To_String (Y, Width => 20));
New_Line;
end Test;
 
begin
Test (61);
Test (109);
Test (181);
Test (277);
end Pells_Equation;</syntaxhighlight>
{{out}}
<pre>
X**2 - 61 * Y**2 = 1 for X = 1766319049 and Y = 226153980
X**2 - 109 * Y**2 = 1 for X = 158070671986249 and Y = 15140424455100
X**2 - 181 * Y**2 = 1 for X = 2469645423824185801 and Y = 183567298683461940
X**2 - 277 * Y**2 = 1 for X = 159150073798980475849 and Y = 9562401173878027020
</pre>
 
=={{header|ALGOL 68}}==
{{Trans|Sidef}} Also tests for a trival solution only (if n is a perfect square only 1, 0 is solution).
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
<langsyntaxhighlight lang="algol68">BEGIN
# find solutions to Pell's eqauation: x^2 - ny^2 = 1 for integer x, y, n #
MODE BIGINT = LONG LONG INT;
Line 57 ⟶ 166:
print( ("x^2 - ", whole( n, -3 ), " * y^2 = 1 for x = ", whole( v1 OF r, -21), " and y = ", whole( v2 OF r, -21 ), newline ) )
OD
END</langsyntaxhighlight>
{{out}}
<pre>
Line 65 ⟶ 174:
x^2 - 277 * y^2 = 1 for x = 159150073798980475849 and y = 9562401173878027020
</pre>
 
=={{header|Arturo}}==
{{trans|Python}}
 
<syntaxhighlight lang="rebol">solvePell: function [n][
x: to :integer sqrt n
[y, z, r]: @[x, 1, shl x 1]
[e1, e2]: [1, 0]
[f1, f2]: [0, 1]
 
while [true][
y: (r * z) - y
z: (n - y * y) / z
r: (x + y) / z
 
[e1, e2]: @[e2, e1 + e2 * r]
[f1, f2]: @[f2, f1 + f2 * r]
[a, b]: @[e2 + f2 * x, f2]
if 1 = (a*a) - n*b*b ->
return @[a, b]
]
]
 
loop [61 109 181 277] 'n [
[x, y]: solvePell n
print ["x² -" n "* y² = 1 for (x,y) =" x "," y]
]</syntaxhighlight>
 
{{out}}
 
<pre>x² - 61 * y² = 1 for (x,y) = 1766319049 , 226153980
x² - 109 * y² = 1 for (x,y) = 158070671986249 , 15140424455100
x² - 181 * y² = 1 for (x,y) = 2469645423824185801 , 183567298683461940
x² - 277 * y² = 1 for (x,y) = 159150073798980475849 , 9562401173878027020</pre>
 
 
=={{header|C}}==
{{trans|ALGOL 68}}
For n = 277, the x value is not correct because 64-bits is not enough to represent the value.
<langsyntaxhighlight lang="c">#include <math.h>
#include <stdbool.h>
#include <stdint.h>
Line 130 ⟶ 274:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>x^2 - 61 * y^2 = 1 for x = 1766319049 and y = 226153980
Line 140 ⟶ 284:
{{trans|C}}
As with the C solution, the output for n = 277 is not correct because 64-bits is not enough to represent the value.
<langsyntaxhighlight lang="cpp">#include <iomanip>
#include <iostream>
#include <tuple>
Line 189 ⟶ 333:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>x^2 - 61 * y^2 = 1 for x = 1766319049 and y = 226153980
Line 198 ⟶ 342:
=={{header|C sharp|C#}}==
{{trans|Sidef}}
<langsyntaxhighlight lang="csharp">using System;
using System.Numerics;
 
Line 228 ⟶ 372:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>x^2 - 61 * y^2 = 1 for x = 1,766,319,049 and y = 226,153,980
Line 237 ⟶ 381:
=={{header|D}}==
{{trans|C#}}
<langsyntaxhighlight lang="d">import std.bigint;
import std.math;
import std.stdio;
Line 277 ⟶ 421:
writefln("x^2 - %3d * y^2 = 1 for x = %27d and y = %25d", n, x, y);
}
}</langsyntaxhighlight>
{{out}}
<pre>x^2 - 61 * y^2 = 1 for x = 1766319049 and y = 226153980
Line 283 ⟶ 427:
x^2 - 181 * y^2 = 1 for x = 2469645423824185801 and y = 183567298683461940
x^2 - 277 * y^2 = 1 for x = 159150073798980475849 and y = 9562401173878027020</pre>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| Velthuis.BigIntegers}}
{{Trans|Go}}
<syntaxhighlight lang="delphi">
program Pells_equation;
 
{$APPTYPE CONSOLE}
 
uses
System.SysUtils,
Velthuis.BigIntegers;
 
type
TPellResult = record
x, y: BigInteger;
end;
 
function SolvePell(nn: UInt64): TPellResult;
var
n, x, y, z, r, e1, e2, f1, t, u, a, b: BigInteger;
begin
n := nn;
x := nn;
x := BigInteger.Sqrt(x);
y := BigInteger(x);
z := BigInteger.One;
r := x shl 1;
 
e1 := BigInteger.One;
e2 := BigInteger.Zero;
f1 := BigInteger.Zero;
b := BigInteger.One;
 
while True do
begin
y := (r * z) - y;
z := (n - (y * y)) div z;
r := (x + y) div z;
 
u := BigInteger(e1);
e1 := BigInteger(e2);
e2 := (r * e2) + u;
 
u := BigInteger(f1);
f1 := BigInteger(b);
 
b := r * b + u;
a := e2 + x * b;
 
t := (a * a) - (n * b * b);
 
if t = 1 then
begin
with Result do
begin
x := BigInteger(a);
y := BigInteger(b);
end;
Break;
end;
end;
end;
 
const
ns: TArray<UInt64> = [61, 109, 181, 277];
fmt = 'x^2 - %3d*y^2 = 1 for x = %-21s and y = %s';
 
begin
for var n in ns do
with SolvePell(n) do
writeln(format(fmt, [n, x.ToString, y.ToString]));
 
{$IFNDEF UNIX} readln; {$ENDIF}
end.</syntaxhighlight>
 
=={{header|Factor}}==
{{trans|Sidef}}
<langsyntaxhighlight lang="factor">USING: formatting kernel locals math math.functions sequences ;
 
:: solve-pell ( n -- a b )
Line 317 ⟶ 536:
dup solve-pell
"x^2 - %3d*y^2 = 1 for x = %-21d and y = %d\n" printf
] each</langsyntaxhighlight>
{{out}}
<pre>
Line 329 ⟶ 548:
{{trans|Visual Basic .NET}}
'''for n = 277 the result is wrong, I do not know if you can represent such large numbers in FreeBasic!'''
<langsyntaxhighlight lang="freebasic">
Sub Fun(Byref a As LongInt, Byref b As LongInt, c As Integer)
Dim As LongInt t
Line 354 ⟶ 573:
Print Using "x^2 - ### * y^2 = 1 for x = ##################### and y = #####################"; n(i); x; y
Next i
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 366 ⟶ 585:
=={{header|Go}}==
{{trans|Sidef}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 427 ⟶ 646:
fmt.Printf("x^2 - %3d*y^2 = 1 for x = %-21s and y = %s\n", n, x, y)
}
}</langsyntaxhighlight>
 
{{out}}
Line 438 ⟶ 657:
 
=={{header|Haskell}}==
{{trans|C#Julia}}
<syntaxhighlight lang ="haskell">pell :: Integral a => aInteger -> (aInteger, aInteger)
pell n = go (x, 1, x * 2, 1, 0, 0, 1)
where
Line 453 ⟶ 672:
in if a' * a' - n * b' * b' == 1
then (a', b')
else go (y', z', r', e1', e2', f1', f2')</langsyntaxhighlight>
 
<pre>λ> mapM_ print $ pell <$> [61,109,181,277]
Line 463 ⟶ 682:
=={{header|J}}==
 
<langsyntaxhighlight Jlang="j">NB. sqrt representation for continued fraction
sqrt_cf =: 3 : 0
rep=. '' [ 'm d'=. 0 1 [ a =. a0=. <. %: y
Line 479 ⟶ 698:
end.
)
</syntaxhighlight>
</lang>
 
Check that task is actually solved
<langsyntaxhighlight Jlang="j">verify =: 3 : 0
assert. 1 = (*: xy) +/ . * 1 _61 [ echo 61 ; xy =. pell 61
assert. 1 = (*: xy) +/ . * 1 _109 [ echo 109 ; xy =. pell 109
Line 488 ⟶ 707:
assert. 1 = (*: xy) +/ . * 1 _277 [ echo 277 ; xy =. pell 277
)
</syntaxhighlight>
</lang>
{{out}}
<pre> verify ''
Line 506 ⟶ 725:
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">
import java.math.BigInteger;
import java.text.NumberFormat;
Line 592 ⟶ 811:
 
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 615 ⟶ 834:
x = 2,565,007,112,872,132,129,669,406,439,503,954,211,359,492,684,749,762,901,360,167,370,740,763,715,001,557,789,090,674,216,330,243,703,833,040,774,221,628,256,858,633,287,876,949,448,689,668,281,446,637,464,359,482,677,366,420,261,407,112,316,649,010,675,881,349,744,201
y = 27,126,610,172,119,035,540,864,542,981,075,550,089,190,381,938,849,116,323,732,855,930,990,771,728,447,597,698,969,628,164,719,475,714,805,646,913,222,890,277,024,408,337,458,564,351,161,990,641,948,210,581,361,708,373,955,113,191,451,102,494,265,278,824,127,994,180
</pre>
 
=={{header|jq}}==
{{trans|Wren}}
'''Works with gojq, the Go implementation of jq'''
 
'''Preliminaries'''
<syntaxhighlight lang="jq"># If $j is 0, then an error condition is raised;
# otherwise, assuming infinite-precision integer arithmetic,
# if the input and $j are integers, then the result will be an integer.
def idivide($i; $j):
($i % $j) as $mod
| ($i - $mod) / $j ;
def idivide($j):
idivide(.; $j);
 
# input should be a non-negative integer for accuracy
# but may be any non-negative finite number
def isqrt:
def irt:
. as $x
| 1 | until(. > $x; . * 4) as $q
| {$q, $x, r: 0}
| until( .q <= 1;
.q |= idivide(4)
| .t = .x - .r - .q
| .r |= idivide(2)
| if .t >= 0
then .x = .t
| .r += .q
else .
end)
| .r ;
if type == "number" and (isinfinite|not) and (isnan|not) and . >= 0
then irt
else "isqrt requires a non-negative integer for accuracy" | error
end ;</syntaxhighlight>
'''The Task'''
<syntaxhighlight lang="jq">def solvePell:
. as $n
| ($n|isqrt) as $x
| { $x,
y : $x,
z : 1,
r : ($x * 2),
v1 : 1,
v2 : 0,
f1 : 0,
f2 : 1 }
| until(.emit;
.y = .r*.z - .y
| .z = idivide($n - .y*.y; .z)
| .r = idivide(.x + .y; .z)
| .v1 as $t
| .v1 = .v2
| .v2 = .r*.v2 + $t
| .f1 as $t
| .f1 = .f2
| .f2 = .r*.f2 + $t
| (.v2 + .x*.f2) as $a
| .f2 as $b
| if ($a*$a - $n*$b*$b == 1) then .emit = [$a, $b] else . end
).emit ;
(61, 109, 181, 277)
| solvePell as $res
| "x² - \(.)y² = 1 for x = \($res[0]) and y = \($res[1])"</syntaxhighlight>
{{out}}
<pre>
x² - 61y² = 1 for x = 1766319049 and y = 226153980
x² - 109y² = 1 for x = 158070671986249 and y = 15140424455100
x² - 181y² = 1 for x = 2469645423824185801 and y = 183567298683461940
x² - 277y² = 1 for x = 159150073798980475849 and y = 9562401173878027020
</pre>
 
=={{header|Julia}}==
{{trans|C#}}
<langsyntaxhighlight lang="julia">function pell(n)
x = BigInt(floor(sqrt(n)))
y, z, r = x, BigInt(1), x << 1
Line 641 ⟶ 933:
println("x\u00b2 - $target", "y\u00b2 = 1 for x = $x and y = $y")
end
</langsyntaxhighlight>{{out}}
<pre>
x² - 61y² = 1 for x = 1766319049 and y = 226153980
Line 651 ⟶ 943:
=={{header|Kotlin}}==
{{trans|C#}}
<langsyntaxhighlight lang="scala">import java.math.BigInteger
import kotlin.math.sqrt
 
Line 720 ⟶ 1,012:
println("x^2 - %3d * y^2 = 1 for x = %,27d and y = %,25d".format(it, x.value, y.value))
}
}</langsyntaxhighlight>
{{out}}
<pre>x^2 - 61 * y^2 = 1 for x = 1,766,319,049 and y = 226,153,980
Line 726 ⟶ 1,018:
x^2 - 181 * y^2 = 1 for x = 2,469,645,423,824,185,801 and y = 183,567,298,683,461,940
x^2 - 277 * y^2 = 1 for x = 159,150,073,798,980,475,849 and y = 9,562,401,173,878,027,020</pre>
 
=={{header|Lambdatalk}}==
Computing big numbers requires the lib_BN library.
<syntaxhighlight lang="Scheme">
{def pell
{lambda {:n}
{let { {:n :n}
{:x {BN.intPart {BN.sqrt :n}}} // x=int(sqrt(n))
} {pell.r :n :x :x 1 {* 2 :x} 1 0 0 1}
}}}
-> pell
 
{def pell.r
{lambda {:n :x :y :z :r :e1 :e2 :f1 :f2}
{let { {:n :n} {:x :x} {:z :z} {:r :r} // no closure ->
{:e1 :e1} {:e2 :e2} {:f1 :f1} {:f2 :f2} // must reassign :(
{:y {BN.- {BN.* :r :z} :y}} // y=rz-y
} {let { {:n :n} {:x :x} {:y :y} {:r :r}
{:e1 :e1} {:e2 :e2} {:f1 :f1} {:f2 :f2}
{:z {BN.intPart
{BN./ {BN.- :n {BN.* :y :y}} :z}}} // z=(n-y*y)//z
} {let { {:n :n} {:x :x} {:y :y} {:z :z}
{:e1 :e1} {:e2 :e2} {:f1 :f1} {:f2 :f2}
{:r {BN.intPart {BN./ {BN.+ :x :y} :z}}} // r= (x+y)//z
} {let { {:n :n} {:x :x} {:y :y} {:z :z} {:r :r}
{:e1 :e2} // e1=e2
{:e2 {BN.+ {BN.* :r :e2} :e1}} // e2=r*e2+e1
{:f1 :f2} // f1=f2
{:f2 {BN.+ {BN.* :r :f2} :f1}} // f2=r*f2+f1
} {let { {:n :n} {:x :x} {:y :y} {:z :z} {:r :r}
{:e1 :e1} {:e2 :e2} {:f1 :f1} {:f2 :f2}
{:a {BN.+ :e2 {BN.* :x :f2}}} // a=e2+x*f2
{:b :f2} // b=f2
} {if {= {BN.compare {BN.- {BN.* :a :a}
{BN.* :n {BN.* :b :b}}}
1}
0} // a*a-n*b*b == 1
then {div}x{sup 2} - n*y{sup 2} = 1 for n=:n, x=:a, y=:b
else {pell.r :n :x :y :z :r :e1 :e2 :f1 :f2} // do it again
}}}}}}}}
-> pell.r
{S.map pell 61 109 181 277}
->
x^2 - n*y^2 = 1 for n=61, x=1766319049, y=226153980
x^2 - n*y^2 = 1 for n=109, x=158070671986249, y=15140424455100
x^2 - n*y^2 = 1 for n=181, x=2469645423824185801, y=183567298683461940
x^2 - n*y^2 = 1 for n=277, x=159150073798980475849, y=9562401173878027020
</syntaxhighlight>
 
=={{header|langur}}==
{{trans|D}}
<syntaxhighlight lang="langur">val .fun = fn(.a, .b, .c) { [.b, .b * .c + .a] }
{{works with|langur|0.10}}
Prior to 0.10, multi-variable declaration/assignment would use parentheses around variable names and values.
 
<lang langur>val .fun = f [.b, .b x .c + .a]
 
val .solvePell = ffn(.n) {
val .x = truncatetrunc .n ^/ 2
var .y, .z, .r = .x, 1, .x x* 2
var .e1, .e2, .f1, .f2 = 1, 0, 0, 1
 
for {
.y = .r x* .z - .y
.z = (.n - .y x* .y) \ .z
.r = (.x + .y) \ .z
.e1, .e2 = .fun(.e1, .e2, .r)
.f1, .f2 = .fun(.f1, .f2, .r)
val .b, .a = .fun(.e2, .f2, .x)
if .a^2 - .n x* .b^2 == 1: return [.a, .b]
}
}
 
val .C = ffn(.x) {
# format number string with commas
var .neg, .s = ZLS"", toStringstring .x
if .s[1] == '-' {
.neg, .s = "-", rest .s
Line 761 ⟶ 1,099:
for .n in [61, 109, 181, 277, 8941] {
val .x, .y = .solvePell(.n)
writeln $"x² - \.n;y² = 1 for:\n\tx = \.x:.fn C;\n\ty = \.y:.fn C;\n"
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 786 ⟶ 1,124:
y = 27,126,610,172,119,035,540,864,542,981,075,550,089,190,381,938,849,116,323,732,855,930,990,771,728,447,597,698,969,628,164,719,475,714,805,646,913,222,890,277,024,408,337,458,564,351,161,990,641,948,210,581,361,708,373,955,113,191,451,102,494,265,278,824,127,994,180
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">FindInstance[x^2 - 61 y^2 == 1, {x, y}, PositiveIntegers]
FindInstance[x^2 - 109 y^2 == 1, {x, y}, PositiveIntegers]
FindInstance[x^2 - 181 y^2 == 1, {x, y}, PositiveIntegers]
FindInstance[x^2 - 277 y^2 == 1, {x, y}, PositiveIntegers]</syntaxhighlight>
{{out}}
<pre>{{x -> 1766319049, y -> 226153980}}
{{x -> 158070671986249, y -> 15140424455100}}
{{x -> 2469645423824185801, y -> 183567298683461940}}
{{x -> 159150073798980475849, y -> 9562401173878027020}}</pre>
 
=={{header|Nim}}==
{{trans|Python}}
{{libheader|bignum}}
<langsyntaxhighlight Nimlang="nim">import math, strformat
import bignum
 
Line 813 ⟶ 1,162:
for n in [61, 109, 181, 277]:
let (x, y) = solvePell(n)
echo &"x² - {n:3} * y² = 1 for (x, y) = ({x:>21}, {y:>19})"</langsyntaxhighlight>
 
{{out}}
Line 820 ⟶ 1,169:
x² - 181 * y² = 1 for (x, y) = ( 2469645423824185801, 183567298683461940)
x² - 277 * y² = 1 for (x, y) = (159150073798980475849, 9562401173878027020)</pre>
 
=={{header|Pascal}}==
{{libheader|IntXLib4Pascal}}
A console application in Free Pascal, created with the Lazarus IDE.
 
Pascal has no built-in support for arbitrarily large integers. The program below requires integers larger than 64 bits, and therefore uses an external library. The code could easily be adapted to solve the negative Pell equation x^2 - n*y^2 = -1, or show that no solution exists.
<syntaxhighlight lang="pascal">
program Pell_console;
uses SysUtils,
uIntX; // uIntX is a unit in the library IntXLib4Pascal.
// uIntX.TIntX is an arbitrarily large integer.
 
// For the given n: if there are non-trivial solutions of x^2 - n*y^2 = 1
// in non-negative integers (x,y), return the smallest.
// Else return the trivial solution (x,y) = (1,0).
procedure SolvePell( n : integer; out x, y : uIntX.TIntX);
var
m, a, c, d : integer;
p, q, p_next, q_next, p_prev, q_prev : uIntX.TIntX;
evenNrSteps : boolean;
begin
if (n >= 0) then m := Trunc( Sqrt( 1.0*n + 0.5)) // or use Rosetta Code Isqrt
else m := 0;
if n <= m*m then begin // if n is not a positive non-square
x := 1; y := 0; exit; // return a trivial solution
end;
c := m; d := 1;
p := 1; q := 0;
p_prev := 0; q_prev := 1;
a := m;
evenNrSteps := true;
repeat
// Get the next convergent p/q in the continued fraction for sqrt(n)
p_next := a*p + p_prev;
q_next := a*q + q_prev;
p_prev := p; p := p_next;
q_prev := q; q := q_next;
// Get the next term a in the continued fraction for sqrt(n)
Assert((n - c*c) mod d = 0); // optional sanity check
d := (n - c*c) div d;
a := (m + c) div d;
c := a*d - c;
evenNrSteps := not evenNrSteps;
until (c = m) and (d = 1);
{
If the first return to (c,d) = (m,1) occurs after an even number of steps,
then p^2 - n*q^2 = 1, and there is no solution to x^2 - n*y^2 = -1.
Else p^2 - n*q^2 = -1, and to get a solution to x^2 - n*y^2 = 1 we can
either continue until we return to (c,d) = (m,1) for the second time,
or use the short cut below.
}
if evenNrSteps then begin
x := p; y := q;
end
else begin
x := 2*p*p + 1; y := 2*p*q
end;
end;
 
// For the given n: show the Pell solution on the console.
procedure ShowPellSolution( n : integer);
var
x, y : uIntX.TIntX;
lineOut : string;
begin
SolvePell( n, x, y);
lineOut := SysUtils.Format( 'n = %d --> (', [n]);
lineOut := lineOut + x.ToString + ', ' + y.ToString + ')';
WriteLn( lineOut);
end;
 
// Main routine
begin
ShowPellSolution( 61);
ShowPellSolution( 109);
ShowPellSolution( 181);
ShowPellSolution( 277);
end.
</syntaxhighlight>
{{out}}
<pre>
n = 61 --> (1766319049, 226153980)
n = 109 --> (158070671986249, 15140424455100)
n = 181 --> (2469645423824185801, 183567298683461940)
n = 277 --> (159150073798980475849, 9562401173878027020)
</pre>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub solve_pell {
my ($n) = @_;
 
Line 856 ⟶ 1,291:
my ($x, $y) = solve_pell($n);
printf("x^2 - %3d*y^2 = 1 for x = %-21s and y = %s\n", $n, $x, $y);
}</langsyntaxhighlight>
{{out}}
<pre>
Line 870 ⟶ 1,305:
{{libheader|Phix/mpfr}}
This now ignores the nonsquare part of the task spec, returning {1,0}.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>include mpfr.e
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
 
procedure fun(mpz a,b,t, integer c)
<span style="color: #008080;">include</span> <span style="color: #7060A8;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
-- {a,b} = {b,c*b+a} (and t gets trashed)
mpz_set(t,a)
<span style="color: #008080;">procedure</span> <span style="color: #000000;">fun</span><span style="color: #0000FF;">(</span><span style="color: #004080;">mpz</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">)</span>
mpz_set(a,b)
<span style="color: #000080;font-style:italic;">-- {a,b} = {b,c*b+a} (and t gets trashed)</span>
mpz_mul_si(b,b,c)
<span style="color: #7060A8;">mpz_set</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)</span>
mpz_add(b,b,t)
<span style="color: #7060A8;">mpz_set</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
end procedure
<span style="color: #7060A8;">mpz_mul_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">)</span>
 
<span style="color: #7060A8;">mpz_add</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t</span><span style="color: #0000FF;">)</span>
function SolvePell(integer n)
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
integer x = floor(sqrt(n)), y = x, z = 1, r = x*2
mpz e1 = mpz_init(1), e2 = mpz_init(),
<span style="color: #008080;">function</span> <span style="color: #000000;">SolvePell</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
f1 = mpz_init(), f2 = mpz_init(1),
<span style="color: #004080;">integer</span> <span style="color: #000000;">x</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sqrt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)),</span> <span style="color: #000000;">y</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">z</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">*</span><span style="color: #000000;">2</span>
t = mpz_init(0), u = mpz_init(),
<span style="color: #004080;">mpz</span> <span style="color: #000000;">e1</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_init</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">),</span> <span style="color: #000000;">e2</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_init</span><span style="color: #0000FF;">(),</span>
a = mpz_init(1), b = mpz_init(0)
<span style="color: #000000;">f1</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_init</span><span style="color: #0000FF;">(),</span> <span style="color: #000000;">f2</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_init</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">),</span>
if x*x!=n then
<span style="color: #000000;">t</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_init</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">),</span> <span style="color: #000000;">u</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_init</span><span style="color: #0000FF;">(),</span>
while mpz_cmp_si(t,1)!=0 do
<span style="color: #000000;">a</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_init</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">),</span> <span style="color: #000000;">b</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_init</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
y = r*z - y
<span style="color: #008080;">if</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">*</span><span style="color: #000000;">x</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">n</span> <span style="color: #008080;">then</span>
z = floor((n-y*y)/z)
<span style="color: #008080;">while</span> <span style="color: #7060A8;">mpz_cmp_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">do</span>
r = floor((x+y)/z)
<span style="color: #000000;">y</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">r</span><span style="color: #0000FF;">*</span><span style="color: #000000;">z</span> <span style="color: #0000FF;">-</span> <span style="color: #000000;">y</span>
fun(e1,e2,t,r) -- {e1,e2} = {e2,r*e2+e1}
<span style="color: #000000;">z</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">((</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">y</span><span style="color: #0000FF;">*</span><span style="color: #000000;">y</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">z</span><span style="color: #0000FF;">)</span>
fun(f1,f2,t,r) -- {f1,f2} = {f2,r*r2+f1}
<span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">((</span><span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">y</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">z</span><span style="color: #0000FF;">)</span>
mpz_set(a,f2)
<span style="color: #000000;">fun</span><span style="color: #0000FF;">(</span><span style="color: #000000;">e1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">e2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t</span><span style="color: #0000FF;">,</span><span style="color: #000000;">r</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- {e1,e2} = {e2,r*e2+e1}</span>
mpz_set(b,e2)
<span style="color: #000000;">fun</span><span style="color: #0000FF;">(</span><span style="color: #000000;">f1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">f2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t</span><span style="color: #0000FF;">,</span><span style="color: #000000;">r</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- {f1,f2} = {f2,r*r2+f1}</span>
fun(b,a,t,x) -- {b,a} = {f2,x*f2+e2}
<span style="color: #7060A8;">mpz_set</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">f2</span><span style="color: #0000FF;">)</span>
mpz_mul(t,a,a)
<span style="color: #7060A8;">mpz_set</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">e2</span><span style="color: #0000FF;">)</span>
mpz_mul_si(u,b,n)
<span style="color: #000000;">fun</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t</span><span style="color: #0000FF;">,</span><span style="color: #000000;">x</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- {b,a} = {f2,x*f2+e2}</span>
mpz_mul(u,u,b)
<span style="color: #7060A8;">mpz_mul</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)</span>
mpz_sub(t,t,u) -- t = a^2-n*b^2
<span style="color: #7060A8;">mpz_mul_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">u</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
end while
<span style="color: #7060A8;">mpz_mul</span><span style="color: #0000FF;">(</span><span style="color: #000000;">u</span><span style="color: #0000FF;">,</span><span style="color: #000000;">u</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
end if
<span style="color: #7060A8;">mpz_sub</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t</span><span style="color: #0000FF;">,</span><span style="color: #000000;">u</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- t = a^2-n*b^2</span>
return {a, b}
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">split_into_chunks</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">one</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">rest</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">x</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">one</span><span style="color: #0000FF;">]}</span>
<span style="color: #000000;">x</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">[</span><span style="color: #000000;">one</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..$]</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">l</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">l</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">min</span><span style="color: #0000FF;">(</span><span style="color: #000000;">l</span><span style="color: #0000FF;">,</span><span style="color: #000000;">rest</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">x</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">k</span><span style="color: #0000FF;">])</span>
<span style="color: #000000;">x</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..$]</span>
<span style="color: #000000;">l</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">k</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">return</span> <span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">&</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">' '</span><span style="color: #0000FF;">,</span><span style="color: #000000;">29</span><span style="color: #0000FF;">))&</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">&</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">' '</span><span style="color: #0000FF;">,</span><span style="color: #000000;">17</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">ns</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">61</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">109</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">181</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">277</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">8941</span><span style="color: #0000FF;">}</span>
sequence ns = {4, 61, 109, 181, 277, 8941}
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ns</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
for i=1 to length(ns) do
<span style="color: #004080;">integer</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">ns</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
integer n = ns[i]
<span style="color: #004080;">mpz</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">SolvePell</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
mpz {x, y} = SolvePell(n)
<span style="color: #004080;">string</span> <span style="color: #000000;">xs</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_get_str</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">comma_fill</span><span style="color: #0000FF;">:=</span><span style="color: #004600;">true</span><span style="color: #0000FF;">),</span>
string xs = mpz_get_str(x,comma_fill:=true),
<span style="color: #000000;">ys</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_get_str</span><span style="color: #0000FF;">(</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span><span style="color: #000000;">comma_fill</span><span style="color: #0000FF;">:=</span><span style="color: #004600;">true</span><span style="color: #0000FF;">)</span>
ys = mpz_get_str(y,comma_fill:=true)
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">xs</span><span style="color: #0000FF;">)></span><span style="color: #000000;">97</span> <span style="color: #008080;">then</span>
printf(1,"x^2 - %3d*y^2 = 1 for x = %27s and y = %25s\n", {n, xs, ys})
<span style="color: #000000;">xs</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">split_into_chunks</span><span style="color: #0000FF;">(</span><span style="color: #000000;">xs</span><span style="color: #0000FF;">,</span><span style="color: #000000;">98</span><span style="color: #0000FF;">,</span><span style="color: #000000;">96</span><span style="color: #0000FF;">)</span>
end for</lang>
<span style="color: #000000;">ys</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">split_into_chunks</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ys</span><span style="color: #0000FF;">,</span><span style="color: #000000;">99</span><span style="color: #0000FF;">,</span><span style="color: #000000;">96</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"x^2 - %3d*y^2 = 1 for x = %27s and y = %25s\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">xs</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ys</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 930 ⟶ 1,386:
</pre>
 
=={{header|Prolog}}==
pell(A, X, Y) finds all solutions X, Y s.t. X^2 - A*Y^2 = 1. Therefore the once() predicate can be used to only select the first one.
<syntaxhighlight lang="prolog">
% Find the square root as a continued fraction
 
cf_sqrt(N, Sz, [A0, Frac]) :-
A0 is floor(sqrt(N)),
(A0*A0 =:= N ->
Sz = 0, Frac = []
;
cf_sqrt(N, A0, A0, 0, 1, 0, [], Sz, Frac)).
 
cf_sqrt(N, A, A0, M0, D0, Sz0, L, Sz, R) :-
M1 is D0*A0 - M0,
D1 is (N - M1*M1) div D0,
A1 is (A + M1) div D1,
(A1 =:= 2*A ->
succ(Sz0, Sz), revtl([A1|L], R, R)
;
succ(Sz0, Sz1), cf_sqrt(N, A, A1, M1, D1, Sz1, [A1|L], Sz, R)).
 
revtl([], Z, Z).
revtl([A|As], Bs, Z) :- revtl(As, [A|Bs], Z).
 
 
% evaluate an infinite continued fraction as a lazy list of convergents.
%
convergents([A0, As], Lz) :-
lazy_list(next_convergent, eval_state(1, 0, A0, 1, As), Lz).
 
next_convergent(eval_state(P0, Q0, P1, Q1, [Term|Ts]), eval_state(P1, Q1, P2, Q2, Ts), R) :-
P2 is Term*P1 + P0,
Q2 is Term*Q1 + Q0,
R is P1 rdiv Q1.
 
 
% solve Pell's equation
%
pell(N, X, Y) :-
cf_sqrt(N, _, D), convergents(D, Rs),
once((member(R, Rs), ratio(R, P, Q), P*P - N*Q*Q =:= 1)),
pell_seq(N, P, Q, X, Y).
 
ratio(N, N, 1) :- integer(N).
ratio(P rdiv Q, P, Q).
 
pell_seq(_, X, Y, X, Y).
pell_seq(N, X0, Y0, X2, Y2) :-
pell_seq(N, X0, Y0, X1, Y1),
X2 is X0*X1 + N*Y0*Y1,
Y2 is X0*Y1 + Y0*X1.
</syntaxhighlight>
{{Out}}
<pre>
% show how we can keep generating solutions for x^2 - 3y^2 = 1
?- pell(3,X,Y).
X = 2,
Y = 1 ;
X = 7,
Y = 4 ;
X = 26,
Y = 15 ;
X = 97,
Y = 56 ;
X = 362,
Y = 209 ;
X = 1351,
Y = 780 ;
X = 5042,
Y = 2911 .
 
% solve the task
?- forall((member(A, [61, 109, 181, 277]), once(pell(A, X, Y))), (write(X**2-A*Y**2=1), nl)).
1766319049**2-61*226153980**2=1
158070671986249**2-109*15140424455100**2=1
2469645423824185801**2-181*183567298683461940**2=1
159150073798980475849**2-277*9562401173878027020**2=1
true.
</pre>
=={{header|Python}}==
{{trans|D}}
<langsyntaxhighlight lang="python">import math
 
def solvePell(n):
Line 953 ⟶ 1,488:
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, y))</langsyntaxhighlight>
{{out}}
<pre>x^2 - 61 * y^2 = 1 for x = 1766319049 and y = 226153980
Line 965 ⟶ 1,500:
{{trans|Perl}}
 
<syntaxhighlight lang="raku" perl6line>use Lingua::EN::Numbers;
 
sub pell (Int $n) {
Line 997 ⟶ 1,532:
my ($x, $y) = pell($n);
printf "x² - %sy² = 1 for:\n\tx = %s\n\ty = %s\n\n", $n, |($x, $y)».&comma;
}</langsyntaxhighlight>
{{out}}
<pre>x² - 61y² = 1 for:
Line 1,021 ⟶ 1,556:
=={{header|REXX}}==
A little extra code was added to align and commatize the gihugeic numbers for readability.
<langsyntaxhighlight lang="rexx">/*REXX program to solve Pell's equation for the smallest solution of positive integers. */
numeric digits 2200 /*ensure enough decimal digs for answer*/
parse arg $ /*obtain optional arguments from the CL*/
Line 1,050 ⟶ 1,585:
parse value f2 r*f2 + f1 with f1 f2
end /*until*/
return e2 + x * f2 f2</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 1,061 ⟶ 1,596:
=={{header|Ruby}}==
{{trans|Sidef}}
<langsyntaxhighlight lang="ruby">def solve_pell(n)
x = Integer.sqrt(n)
y = x
Line 1,081 ⟶ 1,616:
 
[61, 109, 181, 277].each {|n| puts "x*x - %3s*y*y = 1 for x = %-21s and y = %s" % [n, *solve_pell(n)]}
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,090 ⟶ 1,625:
 
</pre>
=={{header|Rust}}==
<syntaxhighlight lang="rust">
use num_bigint::{ToBigInt, BigInt};
use num_traits::{Zero, One};
//use std::mem::replace in the loop if you want this to be more efficient
 
fn main() {
test(61u64);
test(109u64);
test(181u64);
test(277u64);
}
 
struct Pair {
v1: BigInt,
v2: BigInt,
}
 
impl Pair {
pub fn make_pair(a: &BigInt, b: &BigInt) -> Pair {
Pair {
v1: a.clone(),
v2: b.clone(),
}
}
 
}
 
fn solve_pell(n: u64) -> Pair{
let x: BigInt = ((n as f64).sqrt()).to_bigint().unwrap();
if x.clone() * x.clone() == n.to_bigint().unwrap() {
Pair::make_pair(&One::one(), &Zero::zero())
} else {
let mut y: BigInt = x.clone();
let mut z: BigInt = One::one();
let mut r: BigInt = ( &z + &z) * x.clone();
let mut e: Pair = Pair::make_pair(&One::one(), &Zero::zero());
let mut f: Pair = Pair::make_pair(&Zero::zero() ,&One::one());
let mut a: BigInt = Zero::zero();
let mut b: BigInt = Zero::zero();
while &a * &a - n * &b * &b != One::one() {
//println!("{} {} {}", y, z, r);
y = &r * &z - &y;
z = (n - &y * &y) / &z;
r = (&x + &y) / &z;
 
e = Pair::make_pair(&e.v2, &(&r * &e.v2 + &e.v1));
f = Pair::make_pair(&f.v2, &(&r * &f.v2 + &f.v1));
a = &e.v2 + &x * &f.v2;
b = f.v2.clone();
}
let pa = &a;
let pb = &b;
Pair::make_pair(&pa.clone(), &pb.clone())
}
}
 
fn test(n: u64) {
let r: Pair = solve_pell(n);
println!("x^2 - {} * y^2 = 1 for x = {} and y = {}", n, r.v1, r.v2);
}
</syntaxhighlight>
{{out}}
<pre>
x^2 - 61 * y^2 = 1 for x = 1766319049 and y = 226153980
x^2 - 109 * y^2 = 1 for x = 158070671986249 and y = 15140424455100
x^2 - 181 * y^2 = 1 for x = 2469645423824185801 and y = 183567298683461940
x^2 - 277 * y^2 = 1 for x = 159150073798980475849 and y = 9562401173878027020
</pre>
 
=={{header|Scala}}==
<syntaxhighlight lang="scala">def pellFermat(n: Int): (BigInt,BigInt) = {
import scala.math.{sqrt, floor}
 
val x = BigInt(floor(sqrt(n)).toInt)
 
var i = 0
 
// Use the Continued Fractions method
def converge(y:BigInt, z:BigInt, r:BigInt, e1:BigInt, e2:BigInt, f1:BigInt, f2:BigInt ) : (BigInt,BigInt) = {
 
val a = f2 * x + e2
val b = f2
 
if (a * a - n * b * b == 1) {
return (a, b)
}
 
val yh = r * z - y
val zh = (n - yh * yh) / z
val rh = (x + yh) / zh
 
converge(yh,zh,rh,e2,e1 + e2 * rh,f2,f1 + f2 * rh)
}
 
converge(x,BigInt("1"),x << 1,BigInt("1"),BigInt("0"),BigInt("0"),BigInt("1"))
}
 
val nums = List(61,109,181,277)
val solutions = nums.map{pellFermat(_)}
 
{
println("For Pell's Equation, x\u00b2 - ny\u00b2 = 1\n")
(nums zip solutions).foreach{ case (n, (x,y)) => println(s"n = $n, x = $x, y = $y")}
}</syntaxhighlight>
{{out}}
<pre>For Pell's Equation, x² - ny² = 1
 
n = 61, x = 1766319049, y = 226153980
n = 109, x = 158070671986249, y = 15140424455100
n = 181, x = 2469645423824185801, y = 183567298683461940
n = 277, x = 159150073798980475849, y = 9562401173878027020</pre>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func solve_pell(n) {
 
var x = n.isqrt
Line 1,123 ⟶ 1,770:
var (x, y) = solve_pell(n)
printf("x^2 - %3d*y^2 = 1 for x = %-21s and y = %s\n", n, x, y)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,137 ⟶ 1,784:
{{libheader|AttaSwift's BigInt}}
 
<langsyntaxhighlight lang="swift">func solvePell<T: BinaryInteger>(n: T, _ a: inout T, _ b: inout T) {
func swap(_ a: inout T, _ b: inout T, mul by: T) {
(a, b) = (b, b * by + a)
Line 1,176 ⟶ 1,823:
 
print("x\u{00b2} - \(n)y\u{00b2} = 1 for x = \(x) and y = \(y)")
}</langsyntaxhighlight>
 
{{out}}
Line 1,187 ⟶ 1,834:
=={{header|Visual Basic .NET}}==
{{trans|Sidef}}
<langsyntaxhighlight lang="vbnet">Imports System.Numerics
 
Module Module1
Line 1,211 ⟶ 1,858:
Next
End Sub
End Module</langsyntaxhighlight>
{{out}}
<pre>x^2 - 61 * y^2 = 1 for x = 1,766,319,049 and y = 226,153,980
Line 1,222 ⟶ 1,869:
{{libheader|Wren-big}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight ecmascriptlang="wren">import "./big" for BigInt
import "./fmt" for Fmt
 
var solvePell = Fn.new { |n|
Line 1,254 ⟶ 1,901:
var res = solvePell.call(n)
Fmt.print("x² - $3dy² = 1 for x = $-21i and y = $i", n, res[0], res[1])
}</langsyntaxhighlight>
 
{{out}}
Line 1,267 ⟶ 1,914:
{{libheader|GMP}} GNU Multiple Precision Arithmetic Library
{{trans|Raku}}
<langsyntaxhighlight lang="zkl">var [const] BI=Import("zklBigNum"); // libGMP
 
fcn solve_pell(n){
Line 1,283 ⟶ 1,930:
if (A*A - B*B*n == 1) return(A,B);
}
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">foreach n in (T(61, 109, 181, 277)){
x,y:=solve_pell(n);
println("x^2 - %3d*y^2 = 1 for x = %-21d and y = %d".fmt(n,x,y));
}</langsyntaxhighlight>
 
{{out}}
885

edits