方程解决方案在python中设置

时间:2015-12-01 22:12:28

标签: python python-2.7 loops math mathematical-optimization

我有一个问题,我应该制作一个程序来解决这个等式

  

A2 + B2 + C2 = d

并在Lexicographical order中对解决方案进行排序,但是如果没有解决方案打印-1,那么我编写代码并使用三个嵌套循环

d=int(raw_input())
p=0
for a in range(d+1):
    a
    for b in range(d+1):
        b
        for c in range(d+1):
            c
           if a**2+b**2+c**2==d:
                 p=1
                 print a,b,c
                 break
if p==0:
    print -1

超出时间限制的问题输入范围是10 ^ 5简单的输入和输出是清楚的

6

输出

1 1 2
1 2 1
2 1 1

避免时间限制的任何想法?

1 个答案:

答案 0 :(得分:0)

请注意,break语句只会破坏最内部的for循环。 您可能希望使用p并在每个for循环结束时进行检查,即(未检查...):

d=int(raw_input())
p=0
for a in range(d+1):
    a
    for b in range(d+1):
        b
        for c in range(d+1):
            c
           if a**2+b**2+c**2==d:
                 p=1
                 lst =  [a,b,c]
                 lst.sort() 
                 for num in lst:
                    print num,
                 break
        if p==1:
            break
    if p==1:
        break

if p==0:
    print -1