Created
October 27, 2016 04:48
-
-
Save SUPERCILEX/8b7c8f94c3a076b93032d57583a841fa to your computer and use it in GitHub Desktop.
Pythagorean Triples: Think Backwards
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// If you have ever tried computing all the possible pythagorean triples (a^2 + b^2 = c^2) without duplicates, | |
// you might have tried creating 3 nested loops with the first one being a, the second b, and the third c. | |
// This method kind of works, however, you end up with duplicates and unbelievable slow just getting into the hundreds (for c). | |
// A more efficient way to solve the problem would be to start with c being the first loop | |
// and the other two variables in the second and third loop. | |
// Such a method might look like so: | |
for (int i = 0; i < 1000; i++) { | |
for (int j = 0; j < i; j++) { | |
for (int k = 0; k < j; k++) { | |
if (Math.pow(i, 2) == Math.pow(j, 2) + Math.pow(k, 2)) { | |
System.out.println(k + "^2 + " + j + "^2 = " + i + "^2"); | |
// OR | |
System.out.println(i + "^2 = " + j + "^2 + " + k + "^2"); | |
} | |
} | |
} | |
} | |
// At the moment, the most optimized version of the problem I have found that computes all the possible combinations looks like so: | |
for (int i = 5; i < 1000; i++) { | |
for (int j = 4; j < i; j++) { | |
if (j % 2 != 0) { | |
for (int k = 8; k < j; k += 2) { | |
if (Math.pow(i, 2) == Math.pow(j, 2) + Math.pow(k, 2)) { | |
System.out.println(i + "^2 = " + j + "^2 + " + k + "^2"); | |
} | |
} | |
} else { | |
for (int k = 3; k < j; k++) { | |
if (Math.pow(i, 2) == Math.pow(j, 2) + Math.pow(k, 2)) { | |
System.out.println(i + "^2 = " + j + "^2 + " + k + "^2"); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment