从这个问题Java: get greatest common divisor
在获取任何数据类型的gcd时{@ 1}},int
,long
,Integer
,哪个答案在精度,速度,cpu使用方面更好,等?
答:
Long
B:
private static int gcdThing(int a, int b) {
return BigInteger.valueOf(a).gcd(BigInteger.valueOf((b))).intValue();
}
答案 0 :(得分:4)
Random r = new Random();
int[] ints = new int[500000];
for (int i = 0 ; i < ints.length ; i++)
ints[i] = r.nextInt();
for (int i = 0 ; i < ints.length-1; i++)
GCD(i,i+1);
for (int i = 0 ; i < ints.length-1; i++)
gcdThing(i, i + 1);
long start = System.currentTimeMillis();
for (int i = 0 ; i < ints.length-1; i++)
GCD(i,i+1);
System.out.println("GCD: " + (System.currentTimeMillis() - start));
start = System.currentTimeMillis();
for (int i = 0 ; i < ints.length-1; i++)
gcdThing(i, i + 1);
System.out.println("gcdThing: " + (System.currentTimeMillis() - start));
打印:
GCD:13
gcdThing:124