Skip to content

Instantly share code, notes, and snippets.

@giuniu
Created December 12, 2011 17:55
Show Gist options
  • Save giuniu/3c03bb2b423dd78aafbb to your computer and use it in GitHub Desktop.
Save giuniu/3c03bb2b423dd78aafbb to your computer and use it in GitHub Desktop.
原始ピタゴラス数探索ロジック:一般項導出編
import java.util.ArrayList;
import java.util.List;
public class PythagoraSwitch2 {
/**
* @param args
*/
public static void main(String[] args) {
final int MAX = Integer.parseInt(args[0]);
long start = System.nanoTime();
List<PythagorasNum> result = new ArrayList<>();
work:
for (int m = 1; m <= (int) Math.sqrt(MAX); m++) {
int m2 = m * m;
for (int n = m % 2 + 1; n < m; n += 2) {
if (isRelativelyPrime(m, n)) {
int n2 = n * n;
int c = m2 + n2;
if (c > MAX)
continue work;
int a = m2 - n2;
int b = 2 * m * n;
if (a > b) {
int tmp = a;
a = b;
b = tmp;
}
result.add(new PythagorasNum(a, b, c));
}
}
}
long end = System.nanoTime();
System.out.println(result);
System.out.println("count:" + result.size());
System.out.println("time:" + (end - start) / 1000000);
}
private static boolean isRelativelyPrime(int m, int n) {
return gcd(m, n) == 1;
}
private static int gcd(int max, int min) {
int residue = max % min;
return (residue == 0) ? min : gcd(min, residue);
}
private static class PythagorasNum {
final int a;
final int b;
final int c;
PythagorasNum(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override public String toString() {
return "(" + a + ", " + b + ", " + c + ")";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment