0

I wrote a program that looks for a general solution to a Diophantine equation, but the solution is not entirely correct when I check the online calculator. For example, for the equation "45x-128y=177" the solution in general form should be "x=6549-128k" and "y=2301-45k", but I get "x=6549+k128" and "y=-2301+k45". My code:

import re

def extended_gcd(a, b):
    if a == 0:
        return (0, 1)

    (x, y) = extended_gcd(b % a, a)

    return (y - (b // a) * x), x


def gcd(a, b):
    if b == 0:
        return a
    return gcd(b, a % b)


def main():
    s = input('Enter the Diophantine equation: ')
    s1 = re.findall(r'\d+', s)
    a = int(s1[0])
    b = int(s1[1])
    c = int(s1[2])

    d = gcd(a, b)
    print(f'GCD({a},{b}) = {d}')

    if d % c != 0:
        print('This equation has an infinite set of solutions')
        a1 = a // d
        b1 = b // d
        print(f'Short equation: {a1}s + {b1}t = {1}')
        (s, t) = extended_gcd(a1, b1)

        x0 = (c // d) * s
        y0 = (c // d) * t

        print("General solution")
        print(f"x = {x0} + k * {b // d}")
        print(f"y = {y0} + k * {a // d}")
    else:
        print('This equation has no solution')


if __name__ == "__main__":
    main()

What is the problem and how to solve it?

1 Answers1

0

One Python problem you have is your regex does not match negative numbers, ie in your example s1[1] is 128 not -128. To match the sign you can change the regex matching line to

    s1 = re.findall(r'[-+]?\d+', s)

so s1[1] is now the correct -128, as you can check by printing it at the right point

It still does not produce the right answer it seems but at least the inputs should be correct after the fix. You should double check that you coded the algorithm correctly and for example print intermediate results and check them against your by-hand (or Excel) calculations. We can help you with coding problems here but not so much with your algorithm issues...

piterbarg
  • 8,089
  • 2
  • 6
  • 22