Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythagorean triple in Haskell without symmetrical solutions

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?

like image 427
Sierra Avatar asked Aug 31 '11 18:08

Sierra


People also ask

Can Pythagorean triples be all even?

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.

Which of the following is not satisfy the Pythagorean triplet?

∴ 8, 20, 25 do not form a Pythagorean triplet.

Can all three numbers in a Pythagorean triple be odd?

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).


1 Answers

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.

like image 60
sepp2k Avatar answered Oct 12 '22 22:10

sepp2k