最大公约数

欧几里德算法

非负整p,q的最大公约数满足下列条件:

  1. 如果q为0,则最大公约数是p
  2. 否则p,q的最大公约同时也是p%q=r和q的最大公约数

 

English despcription:

Compute the greatest common divisor of two nonnegative integers p and q as follows:

  1. If q is 0, the answer is p. If not, divide p by q and take the remainder r.
  2. The answer is the greatest common divisor of q and r.

Java代码

public static int gcd(int p, int q) {   
    if (q == 0)
         return p; 
     int r = p % q;  
 return gcd(q, r); 
} 

 

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务