Pell's equation: Difference between revisions

Content added Content deleted
 
Line 1,070: Line 1,070:
=={{header|langur}}==
=={{header|langur}}==
{{trans|D}}
{{trans|D}}
<syntaxhighlight lang="langur">val .fun = fn .a, .b, .c: [.b, .b * .c + .a]
<syntaxhighlight lang="langur">
val fun = fn a, b, c: [b, b * c + a]


val .solvePell = fn(.n) {
val solvePell = fn(n) {
val .x = trunc .n ^/ 2
val x = trunc(n ^/ 2)
var .y, .z, .r = .x, 1, .x * 2
var y, z, r = x, 1, x * 2
var .e1, .e2, .f1, .f2 = 1, 0, 0, 1
var e1, e2, f1, f2 = 1, 0, 0, 1


for {
for {
.y = .r * .z - .y
y = r * z - y
.z = (.n - .y * .y) \ .z
z = (n - y * y) \ z
.r = (.x + .y) \ .z
r = (x + y) \ z
.e1, .e2 = .fun(.e1, .e2, .r)
e1, e2 = fun(e1, e2, r)
.f1, .f2 = .fun(.f1, .f2, .r)
f1, f2 = fun(f1, f2, r)
val .b, .a = .fun(.e2, .f2, .x)
val b, a = fun(e2, f2, x)
if .a^2 - .n * .b^2 == 1: return [.a, .b]
if a^2 - n * b^2 == 1: return [a, b]
}
}
}
}


val .C = fn(.x) {
val C = fn(x) {
# format number string with commas
# format number string with commas
var .neg, .s = "", string .x
var neg, s = "", x -> string
if .s[1] == '-' {
if s[1] == '-' {
.neg, .s = "-", rest .s
neg, s = "-", s -> rest
}
}
.neg ~ join ",", split -3, .s
neg ~ join(",", split(-3, s))
}
}


for .n in [61, 109, 181, 277, 8941] {
for n in [61, 109, 181, 277, 8941] {
val .x, .y = .solvePell(.n)
val x, y = solvePell(n)
writeln "x² - {{.n}}y² = 1 for:\n\tx = {{.x:fn C}}\n\ty = {{.y:fn C}}\n"
writeln "x² - {{n}}y² = 1 for:\n\tx = {{x:fn C}}\n\ty = {{y:fn C}}\n"
}
}
</syntaxhighlight>
</syntaxhighlight>