0
votes

i have a problem that i should make a programme to solve this equation

a2 + b2 + c2 = d

and sort the solution in Lexicographical order the order comes without make it and if there is no solution print -1 so i write my Code and i use three nested loops

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

my problem in Time Limit exceeded The input range is 10^5 simple input and output to be clear

6

output

1 1 2
1 2 1
2 1 1

any ideas To Avoid that Time Limit?

1
Hint: why not assume that a >= b >= c to save repeating a whole bunch of triplets, a, b and c? - xnx

1 Answers

0
votes

notice that your break statement breaks only out of the most inner for loop. you may want to use p for that and make checks at the end of each for loop, i.e (it wasn't checked...):

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