Pythagorean triples
No. 87
Q: |
Pythagorean triples are integer combinations of three values being related by the Pythagorean theorem: Sample integer triple examples: For most combinations however at least one value will be of real rather than integer value e.g.: Find all Pythagorean triples of non-zero integer values being smaller than 100 each. Keep the limit of 100 flexible. TipImplement a two-step process:
Use three nested loops for creating all possible combinations. Do not yet bother about possible duplicates. Your result output should look like: Found (4, 3, 5) Found (3, 4, 5) Found (8, 6, 10) Found (6, 8, 10) ... |
|||||||||||||||||||||
A: |
A value of e.g. b == 100 would imply a == 0 contradicting the description. Likewise c == 1 would imply either a == 0 or b == 0; We create all possible combinations by using three nested loops and filtering for the desired results:
This results in: Found (4, 3, 5) Found (3, 4, 5) Found (8, 6, 10) Found (6, 8, 10) Found (12, 5, 13) ... Found (96, 28, 100) Found (80, 60, 100) Found (60, 80, 100) Found (28, 96, 100) Note duplicates like |
No. 88
Avoiding duplicates and gaining performance
Q: |
There are several issues with the previous solution:
The problem can thus be restated to find the set of all triples simultaneously obeying: Your solution shall account for both the number of combinations being evaluated and the number of Pythagorean triples being found creating a final line like: ... (60, 63, 87) (60, 80,100) (65, 72, 97) 52 triples found by filtering 33338 combinations Your solution should find all 52 triples by filtering from at most 33338 combinations. If you do need less combinations in the first place please let me know. I'm more than happy publishing an enhanced solution. |
A: |
Based on our previous solution we introduce the following changes:
Piecing together these snippets and adding two variables
Result: ( 3, 4, 5) ( 5, 12, 13) ... (65, 72, 97) 52 triples found by filtering 33338 combinations In essence we reduced the number of triples being constructed in the first place from nearly a million to just 33338. This is just 3% resulting in much shorter execution time. |