Java 解释互质检查是如何工作的

Java 解释互质检查是如何工作的,java,performance,greatest-common-divisor,Java,Performance,Greatest Common Divisor,每次我用欧几里德方法检查两个数字是否是同素数。但是有一个解决方案使用了这个代码来检查共素数,这个方法所花费的时间比欧几里德方法要快得多:() 我不明白这是怎么回事。(我确实理解位运算。)例如,这些行是什么意思 if (((u | v) & 1) == 0) return false; 为什么只返回false?还有其他一些我无法理解正在发生的事情。如果你们中有人能给我一些演练,这将非常有帮助。您发布的代码是对的修改。以下是我的注释: private static boolean

每次我用欧几里德方法检查两个数字是否是同素数。但是有一个解决方案使用了这个代码来检查共素数,这个方法所花费的时间比欧几里德方法要快得多:()

我不明白这是怎么回事。(我确实理解位运算。)例如,这些行是什么意思

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

为什么只返回false?还有其他一些我无法理解正在发生的事情。如果你们中有人能给我一些演练,这将非常有帮助。

您发布的代码是对的修改。以下是我的注释:

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;
}

你能给我解释一下这个代码的另一部分吗。。如果可能的话?@user4890159还有什么其他部分?@user4890159在每次迭代中,你将
u
v
分开,直到两者都是奇数(或者
0
,也就是位移位魔法所做的),然后更新
u
v
。你可能想看看
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;
}