How can I iterate (loop) over i, j values in order?

85 Views Asked by At

I have this code to find Pythagorean triplets:

for i in range(1,31):
    for j in range(1,31):
        for k in range(1,31):
            if((i**2 + j**2)==(k**2)):
                print(i,",",j,",",k)

I get this result:

3 , 4 , 5
4 , 3 , 5
5 , 12 , 13
6 , 8 , 10
7 , 24 , 25
8 , 6 , 10
8 , 15 , 17
9 , 12 , 15
10 , 24 , 26
12 , 5 , 13
12 , 9 , 15
12 , 16 , 20
15 , 8 , 17
15 , 20 , 25
16 , 12 , 20
18 , 24 , 30
20 , 15 , 25
20 , 21 , 29
21 , 20 , 29
24 , 7 , 25
24 , 10 , 26
24 , 18 , 30

The problem is that the triplets are duplicated, because each i, j pair will be shown in either order. How can I prevent this?

2

There are 2 best solutions below

0
Mislah On

Here in your code, the repetition is caused by checking both i²+j² and j²+i². Once we check for i²+j² it is no longer required to check the other one. So it's best to keep either of the variable be always greater than the other. That is, make the second loop starts from i.

The code after required changes:

for i in range(1,31):
    for j in range(i,31):
        for k in range(1,31):
            if((i**2 + j**2)==(k**2)):
                print(i,",",j,",",k)
0
Unamata Sanatarai On

The innermost loop (k) starts from j+1, therefore we are looking only at the values greater than j. this is enough to eliminate duplicates.

for i in range (1, 31):
    for j in range(i, 31):
        for k in range (j+1, 31):
            if ((i**2 + j**2) == (k**2)):
                print(i, ",", j, ",", k)

output:

3 , 4 , 5
5 , 12 , 13
6 , 8 , 10
7 , 24 , 25
8 , 15 , 17
9 , 12 , 15
10 , 24 , 26
12 , 16 , 20
15 , 20 , 25
18 , 24 , 30
20 , 21 , 29