最大公約數和最小公倍數

#pragma once

class CommonCalc
{
public: 
    CommonCalc() {}

    //最大公約數 Greatest Common Divisor
    static long gcd(long x,long y)
    {
        long t;
        if (x == 0 || y == 0) return 0;
        if (x < y) //交換,保證X >Y
        {
            t = x;
            x = y;
            y = t;
        }
        while((t = x % y) != 0) // 展轉相除法
        {
            x = y;
            y = t;
        }
        return y;
    }

    // 最小公倍數(Least Common Multiple)
    static long lcm(long x,long y)    //用到gcd
    {
        return x / gcd(x, y) * y;
    }
};
相關文章
相關標籤/搜索