How does the Euclidean Algorithm work?

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

    given that 'q' is never used, I don't see a difference between your plain iterative function, and the recursive iterative function... both do

    gdc(first number, second number)
      as long as (second number > 0) {
          int remainder = first % second;
          gcd = try(second as first, remainder as second);
      }
    }
    

    Barring trying to apply this to non-integers, under which circumstances does this algorithm fail?

    (also see http://en.wikipedia.org/wiki/Euclidean_algorithm for lots of detailed info)

提交回复
热议问题