How does the Euclidean Algorithm work?

前端 未结 5 675
误落风尘
误落风尘 2020-12-08 23:12

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) {
                 


        
5条回答
  •  一生所求
    2020-12-08 23:50

    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").

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

    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.

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

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

    1. If r = 0 then a = bq, and so b divides both b and a. Hence gcd(a,b)=b.
    2. Otherwise (r > 0), we can reduce the problem of finding gcd(a,b) to the problem of finding gcd(b,r) which is exactly the same number (as a, b and r are all divisible by d).

    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.

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

提交回复
热议问题