Skip to content
Advertisement

All Pythagorean Triplets in a range

If I want to find all the Pythagorean Triplets in a specific range, I wrote the following code:

JavaScript

But unfortunately I got duplicated triplets, for example: 3, 4, 5 and 4, 3, 5
How can I overcome this?

Advertisement

Answer

You can remove duplicates by changing your loops, particularly where each one starts:

JavaScript

Notice that the inner loop is unnecessary since you can calculate c directly from a and b. You just have to check if the calculated value is an integer:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement