美文网首页
lintcode 845 Greatest Common Div

lintcode 845 Greatest Common Div

作者: Anseis | 来源:发表于2018-04-07 02:43 被阅读0次

本来写算法的,碰到了N年未遇到的数学问题,欧几里得辗转相除法求最大公约数

举个例子吧,原理说了费劲

120 42之间的GCD

120 % 42 = 36

接下来进行
42 % 36 = 6

接下来
36 % 6 = 0
那么结果出来了,最后一个可以整除的除数就是结果

代码如下

public class Solution {
   /**
    * @param a: the given number
    * @param b: another number
    * @return: the greatest common divisor of two numbers
    */
   public int gcd(int a, int b) {
       // write your code here
       
       while(a % b != 0){
           int tmp = a;
           a = b;
           b = tmp % b;
       }
       return b;
   }
}

相关文章

网友评论

      本文标题:lintcode 845 Greatest Common Div

      本文链接:https://www.haomeiwen.com/subject/deyehftx.html