For solving a Pell's equation How many iterations should I run before confirming no solution exists.

144 Views Asked by At

I am running this piece of code from rosettacode

import math
def solvePell(n):
    x = int(math.sqrt(n))
    y, z, r = x, 1, 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 = f2 * x + e2, f2
        if a * a - n * b * b == 1:
            return a, b

Source https://rosettacode.org/wiki/Pell%27s_equation#Python

however rosettacode doesn't handle cases when no solution exists. How many iterations should I run before ensuring no solution exists.

1

There are 1 best solutions below

5
On BEST ANSWER

Just add at the beginning of your function:

if math.sqrt(n)**2 == n:
    return -1,-1