Skip to content

Instantly share code, notes, and snippets.

@okathira
Last active February 18, 2021 16:43
Show Gist options
  • Save okathira/34a130471f8ae5aebec26a072d8584f0 to your computer and use it in GitHub Desktop.
Save okathira/34a130471f8ae5aebec26a072d8584f0 to your computer and use it in GitHub Desktop.
show or count non-duplicated Pythagorean triple (a < b < c) combinations in JAVA. OEIS: http://oeis.org/A046083, http://oeis.org/A046084, http://oeis.org/A009000
package pythagoras;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
public class Pythagoras {
static private class Triples {
private int a;
private int b;
private int c;
Triples(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Triples)) return false;
Triples triples = (Triples) o;
return a == triples.a &&
b == triples.b &&
c == triples.c;
}
@Override
public int hashCode() {
return Objects.hash(a, b, c);
}
@Override
public String toString() {
return "(" +
"a=" + a +
", b=" + b +
", c=" + c +
')';
}
}
static private Set<Triples> getPythagoreanTriples(int n) { // with hypotenuse n or less
Set<Triples> pythagoreanTriples = new HashSet<>();
for (int l = 1; l * l + (l + 1) * (l + 1) <= n; l++) {
for (int m = l + 1; l * l + m * m <= n; m++) {
int a = m * m - l * l;
int b = 2 * m * l;
int c = m * m + l * l;
if (a > b) {
int t = a;
a = b;
b = t;
}
for (int k = 1; k * c <= n; k++)
pythagoreanTriples.add(new Triples(k * a, k * b, k * c));
}
}
return pythagoreanTriples;
}
static public void showPythagoreanTriples(int n) {
for (Triples t : getPythagoreanTriples(n))
System.out.println(t);
}
static public int countPythagoreanTriples(int n) {
return getPythagoreanTriples(n).size();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment