Created
December 12, 2011 17:54
-
-
Save giuniu/b4c4ea875ad8c4c8455f to your computer and use it in GitHub Desktop.
原始ピタゴラス数探索ロジック:しらみつぶし編
This file contains hidden or 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
import java.util.ArrayList; | |
import java.util.List; | |
public class PythagoraSwitch { | |
public static void main(String[] args) { | |
final int MAX = Integer.parseInt(args[0]); | |
long start = System.nanoTime(); | |
List<PythagorasNum> result = new ArrayList<>(); | |
for (int c = 3; c <= MAX; c += 2) { | |
long c2 = ((long) c) * c; | |
for (int b = c - 1; true; b--) { | |
long b2 = ((long) b) * b; | |
long a2 = c2 - b2; | |
if (a2 >= b2) | |
break; | |
int a = (int) Math.sqrt(a2); | |
if (((long) a) * a == a2 && isRelativelyPrime(c, b, a)) | |
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 c, int b, int a) { | |
return gcd(c, gcd(b, a)) == 1; | |
} | |
private static int gcd(int max, int min) { | |
for (int residue; (residue = max % min) != 0; ) { | |
max = min; | |
min = residue; | |
} | |
return min; | |
} | |
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