Python 当x^2+;y^2=n,其中n为输入

Python 当x^2+;y^2=n,其中n为输入,python,Python,是否可以编写一个不使用函数就能找到解决方案的程序?我对它不太熟悉。以下是我在Python 3.9中的尝试: n = int(input("enter a number: ")) while n>0: for x in range(0,n): x **= 2 print("this is x:", x) for y in range(0,n): y **= 2

是否可以编写一个不使用函数就能找到解决方案的程序?我对它不太熟悉。以下是我在Python 3.9中的尝试:

n = int(input("enter a number: "))

while n>0:
    for x in range(0,n):
        x **= 2
        print("this is x:", x)
        for y in range(0,n):
            y **= 2
            n = x+y
            print("this is y:", y)

            if n == x+y:
                print(x,y)
            else:
                print(n, "has no solution")

预期的结果是当n可以是任何正整数时,找到x和y。例如,x^2+y^2=9。解为(3,0)和(0,3)。感谢所有帮助过我的人。

如果我正确理解了任务,您需要用整数解x^2+y^2=n。这是我的密码

n = int(input("enter a number: "))
sqrt = {} # key: square of integer, value: square root of it
# assume that x >= y, otherwise, swap
x = 0
while x * x <= n:
    x_square = x * x
    # check if solution exists
    if n - x_square in sqrt:
        print(f'x={x} and y={sqrt[n-x_square]} satisfy x^2+y^2={n}')
        print(f'x={sqrt[n-x_square]} and y={x} satisfy x^2+y^2={n}')
    sqrt[x_square] = x
    x += 1
UPD2:修复了我的解决方案,使其不满足任何函数要求。

您可以通过在x和y上的嵌套循环(其中y>=x)轻松地“暴力”执行此操作,以查找反转,而无需遍历所有的循环

n = 9
for x in range(n):
    for y in range(x,n+1):
        if x*x + y*y == n:
            print(*{(x,y),(y,x)}) # only print one solution if x==y

(0, 3) (3, 0)
如果要对此进行优化,可以在剩余值超过目标值时中断循环:

n = 9
for x in range(n):
    if x*x > n:                    # if x^2 already greater than n
        break                      # no higher value of x will work either
    for y in range(x,n+1):
        if x*x + y*y == n:
            print(*{(x,y),(y,x)})
        elif x*x + y*y > n:        # if y already gives a result > n for this x
            break                  # then no higher value of y will work   
一种更高级的技术是建立一个最大为n的正方形字典,并查找存在等于n-x^2的正方形的任何x值:

n      = 9
y2     = {y*y:y for y in range(n+1)}
result = [(x,y2[n-x*x]) for x in range(n+1) if n-x*x in y2]

print(*result or {"no solution"}) # (0, 3) (3, 0)
                         

这是圆的方程式。有无限的解决方案。如果你想画圆,你需要先解方程,然后计算你想计算的任何东西,例如
y
n是数字,程序会找到至少两个解,因此当插入方程时,它等于n。不确定它怎么会有无限解。你是说整数解吗?否则,任何n都有无穷多的解。我重复一遍,这是一个圆的方程。因为圆上有无限多个点,所以有无限多个解
3,0
0,3
是圆截取x轴和y轴的坐标,它不接近。非常感谢您的反馈,我非常感谢。我将把它实现到我的代码中。请您告诉我,如果没有找到解决方案,会发生什么?有时,整数中没有解决方案。例如,x^2+y^2=3没有整数解。在这种情况下,我认为打印“无解决方案”将是一个好主意。因此,我需要跟踪是否为x和y的任何组合找到了解决方案,如果没有,则不打印任何解决方案为实现此目标,我在开始时说
solution\u found=False
(尚未找到解决方案),并在找到解决方案后将其值更改为True。如果循环未找到任何解决方案,则
solution\u found
仍为False,因此
not solution\u found
不为False,即为true。对于代码的最后两行,如果
solution\u found
为true,为什么不打印解决方案?谢谢您的帮助。我将在将来实施您的反馈。
n      = 9
y2     = {y*y:y for y in range(n+1)}
result = [(x,y2[n-x*x]) for x in range(n+1) if n-x*x in y2]

print(*result or {"no solution"}) # (0, 3) (3, 0)