Java:获得最大公约数,哪种方法更好?

时间:2014-02-05 07:16:04

标签: java greatest-common-divisor

从这个问题Java: get greatest common divisor

在获取任何数据类型的gcd时{@ 1}},intlongInteger,哪个答案在精度,速度,cpu使用方面更好,等?

答:

Long

B:

private static int gcdThing(int a, int b) {
    return BigInteger.valueOf(a).gcd(BigInteger.valueOf((b))).intValue();
}

1 个答案:

答案 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