最大公約數 + 最小公倍數

最大公約數(Greatest Common Divisor, GCD)

歐幾里得算法:計算兩個非負整數p和q的最大公約數:若q是0,則最大公約數是p;不然,將p除以q獲得餘數r,p和q的最大公約數即爲q和r的最大公約數。算法

遞歸spa

1 int gcd_recursion(int p, int q){
2     //p >= q
3     if( q == 0 )
4       return p;
5       
6     int r = p%q;
7     return gcd_recursion( q, r);
8 }

迭代code

int gcd_itera(int p, int q){
    if( p < q ){
        int tmp = p;
        p = q;
        q = tmp;
    }
    
    if( q == 0 )
      return p;
    while( p > 0 ){
        int r = p%q;
        p = q;
        q = r;
        if( r == 0 )
          break;
    }
    return p;
}

最小公倍數(Maximum Common Multiple,MCM)

最小公倍數 = 數1 * 數2 * gcd(數1, 數2)blog

1 int mcm(int p, int q){
2     return p*q*gcd_itera(p, q);
3 }
相關文章
相關標籤/搜索