最大公约数和最小公倍数

#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;
    }
};

 

posted @ 2014-11-10 15:15  rain_2012_qf  阅读(123)  评论(0编辑  收藏  举报