0

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?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • 1
    I would advice using the formula for Pythagorian triples: `a = m**2 - n**2; b = 2*m*n; c = m**2 + n**2` for any two distinct integers `m, n`. – B Remmelzwaal Feb 17 '23 at 14:35
  • 1
    Welcome to Stack Overflow. Aside from solving the ordering problem, **it does not make sense** to loop over possible values for `k`; only one possible `k` value could ever possibly fit, for a given `i` and `j`. The real question is **whether** `(i ** 2) + (j ** 2)` is a square number; see [Check if a number is a perfect square](https://stackoverflow.com/questions/2489435). – Karl Knechtel Feb 17 '23 at 14:46

2 Answers2

0

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)
Mislah
  • 318
  • 1
  • 2
  • 11
0

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
Unamata Sanatarai
  • 6,475
  • 3
  • 29
  • 51