I gotta do the Pythagorean triple in Haskell without symmetrical solutions. My try is:
terna :: Int -> [(Int,Int,Int)]
terna x = [(a,b,c)|a<-[1..x], b<-[1..x], c<-[1..x], (a^2)+(b^2) == (c^2)]
and I get as a result:
Main> terna 10
[(3,4,5),(4,3,5),(6,8,10),(8,6,10)]
As you can see, I´m getting symmetrical solutions like: (3,4,5) (4,3,5). I need to get rid of them but I don´t know how. Can anyone help me?
A Pythagorean Triple can never be made of all odd numbers or two even numbers and one odd number. This is true because: The square of an odd number is an odd number and the square of an even number is an even number.
∴ 8, 20, 25 do not form a Pythagorean triplet.
always odd. In addition, one side of every Pythagorean triple is divisible by 3, another by 4, and another by 5. One side may have two of these divisors, as in (8, 15, 17), (7, 24, 25), and (20, 21, 29), or even all three, as in (11, 60, 61).
Every time you have a duplicate you have one version in which a is greater than b and one where b is greater than a. So if you want to make sure you only ever get one of them, you just need to make sure that either a
is always equal to or less than b
or vice versa.
One way to achieve this would be to add it as a condition to the list comprehension.
Another, more efficient way, would be to change b
's generator to b <- [1..a]
, so it only generates values for b
which are smaller or equal to a
.
Speaking of efficiency: There is no need to iterate over c
at all. Once you have values for a
and b
, you could simply calculate (a^2)+(b^2)
and check whether it has a natural square root.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With