如何欧几里得算法的工作吗?欧几里得、算法、工作

2023-09-11 00:00:24 作者:单身菇凉哇咔咔!

我刚刚发现这个算法计算最大公约数在我的课堂笔记:

I just found this algorithm to compute the greatest common divisor in my lecture notes:

public static int gcd( int a, int b ) {
    while (b != 0) {
        final int r = a % b;
        a = b;
        b = r;
    }
    return a;
}

所以研究的是余数时分割的 B 的成的在的(获得MOD)。然后 B 的被分配给的一的,而其余被分配到的 B 的,并一的,则返回。我不能为我看到的生活是如何工作的!

So r is the remainder when dividing b into a (get the mod). Then b is assigned to a, and the remainder is assigned to b, and a is returned. I can't for the life of my see how this works!

和然后,显然该算法并不适用于所有的情况下工作,而这一次然后必须使用:

And then, apparently this algorithm doesn't work for all cases, and this one must then be used:

public static int gcd( int a, int b ) {
    final int gcd;
    if (b != 0) {
        final int q = a / b;
        final int r = a % b; // a == r + q * b AND r == a - q * b.
        gcd = gcd( b, r );
    } else {
        gcd = a;
    }
    return gcd;
}

我不明白这背后的原因。我一般得到递归和我精通Java,但是这是在暗指我。帮助吗?

I don't understand the reasoning behind this. I generally get recursion and am good at Java but this is alluding me. Help please?

推荐答案

维基百科的文章包含了一个解释,但它不容易立刻找到它(也,程序+防爆并不总是回答这个问题:为什么它的工作原理 )。

The Wikipedia article contains an explanation, but it's not easy to find it immediately (also, procedure + proof don't always answer the question "why it works").

基本上它归结为这样一个事实:两个整数的a,b(假设> = b)中,它总是能写信= QB + r其中为r湾

Basically it comes down to the fact that for two integers a, b (assuming a >= b), it is always possible to write a = qb + r where r < b.

如果D = GCD(A,B),那么我们可以写一个= DS和b = DT。因此,我们有DS = QDT + R。因为左手侧是整除d时,右手侧也必须是整除用d。而且,由于QDT是整除研发,得出的结论是,其中r还必须除尽用d。

If d=gcd(a,b) then we can write a=ds and b=dt. So we have ds = qdt + r. Since the left hand side is divisible by d, the right hand side must also be divisible by d. And since qdt is divisible by d, the conclusion is that r must also be divisible by d.

要总结一下:我们有一个= BQ + R,其中R; b和a,b和r均为所有整除最大公约数(A,B)。

To summarise: we have a = bq + r where r < b and a, b and r are all divisible by gcd(a,b).

由于A> = B> R,我们有两种情况:

Since a >= b > r, we have two cases:

如果使r = 0则a = BQ,并因此B划分既b和a。因此,GCD(A,B)= B。 否则(R> 0),就可以减少寻找最大公约数(A,B),以寻找最大公约数(B,R),它是完全相同的数目(作为一个问题,b和r均为所有整除的问题用d)。

为什么这是一个减少?由于R&LT;湾因此,我们现在处理的绝对数量较少。这意味着,我们只有在我们到达R = 0申请本次减持的次数是有限的。

Why is this a reduction? Because r < b. So we are dealing with numbers that are definitely smaller. This means that we only have to apply this reduction a finite number of times before we reach r = 0.

现在,R = A%B的希望解释了code你。

Now, r = a % b which hopefully explains the code you have.