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?
Here in your code, the repetition is caused by checking both
i²+j²andj²+i². Once we check fori²+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 fromi.The code after required changes: