通过python解决Diophotone方程,并希望获得一对非负解

时间:2019-07-04 03:27:06

标签: python python-3.x diophantine

我是一名喜欢编码的本科生,今天遇到了有关二光子方程的问题。问题是:对于ax + by = c,其中a,b,c均为正整数,找到x,y使得x和y均为非负整数,而ax + by = c。

我在下面编写了代码,并尝试使用3x + 7y = 12,但是唯一的解决方案是x = -24,y = 12,这实际上是一个解决方案,但x <0。我无法获得x = 4,y = 0作为根据要求的答案。

def gcd(x,y):
    if y == 0:
        return x
    else:
        return gcd(y,x%y)

def solve(a,b,c):
    d = gcd(a,b)
    if c % d != 0:
        output = 'there are no such integers'
        return output
    else:
        q, r = divmod(a,b)
        if r == 0:
            return ([0, c/b])
        else:
            solution = cents(b, r, c)
            u = solution[0]
            v = solution[1]
            return ([v, u - v * q])
        s = u - v * q
        while v < 0 or s < 0:
            v = v + b/gcd(a,b)
            s = s - a/gcd(a,b)
            continue
        while v >= 0 and s >= 0:
            return ([v,s])

a = int(input("a in a*x + b*y = c:"))

b = int(input("b in a*x + b*y = c:"))

c = int(input("c in a*x + b*y = c:"))

print(solve(a,b,c))

输出为:

a in a*x + b*y = c:3
b in a*x + b*y = c:7
c in a*x + b*y = c:12
[-24, 12]

但是对于这个问题,我希望它是x = 4,y =0。此外,如果我想获得特定的x,y并确保那对x,y,x +应该怎么办? y可能最小吗?预先谢谢你!

0 个答案:

没有答案