解释互质检查的工作原理

时间:2015-06-07 19:07:28

标签: java performance greatest-common-divisor

每次我使用Euclid方法检查两个数字是否是共同素数。但是有一个解决方案使用这个代码来检查共同素数,并且这个时间比Euclid方法快得多:(source

private static boolean isCoprime(long u, long v) {
    if (((u | v) & 1) == 0)
        return false;

    while ((u & 1) == 0)
        u >>= 1;
    if (u == 1)
        return true;

    do {
        while ((v & 1) == 0)
            v >>= 1;
        if (v == 1)
            return true;

        if (u > v) {
            long t = v;
            v = u;
            u = t;
        }
        v -= u;
    } while (v != 0);

    return false;
}

我无法理解这是如何工作的。 (我确实理解按位操作。)例如,这些行是什么意思......

if (((u | v) & 1) == 0)
    return false;

为什么简单地返回false?还有其他一些我无法理解正在发生的事情。如果你们中的任何一个人能够给我一些演练,那将会有很大的帮助。

1 个答案:

答案 0 :(得分:6)

您发布的代码是对binary GCD algorithm的修改。这是我的注释评论:

private static boolean isCoprime(long u, long v) {
    // If both numbers are even, then they are not coprime.
    if (((u | v) & 1) == 0) return false;

    // Now at least one number is odd. Eliminate all the factors of 2 from u.
    while ((u & 1) == 0) u >>= 1;

    // One is coprime with everything else by definition.
    if (u == 1) return true;

    do {
        // Eliminate all the factors of 2 from v, because we know that u and v do not have any 2's in common.
        while ((v & 1) == 0) v >>= 1;

        // One is coprime with everything else by definition.
        if (v == 1) return true;

        // Swap if necessary to ensure that v >= u.
        if (u > v) {
            long t = v;
            v = u;
            u = t;
        }

        // We know that GCD(u, v) = GCD(u, v - u).
        v -= u;
    } while (v != 0);

    // When we reach here, we have v = 0 and GCD(u, v) = current value of u, which is greater than 1.
    return false;
}