How does the Euclidean Algorithm work?

前端 未结 5 708
误落风尘
误落风尘 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:40

    They're equivalent. First thing to notice is that q in the second program is not used at all. The other difference is just iteration vs. recursion.

    As to why it works, the Wikipedia page linked above is good. The first illustration in particular is effective to convey intuitively the "why", and the animation below then illustrates the "how".

提交回复
热议问题