计算最大公约数-更相减损术和移位结合
static void Main(string[] args)
{
    Console.WriteLine("输入两个整数,求最大公约数");
    int a, b;
    Stopwatch stopwatch = new Stopwatch();
    while (true) {
        a = Convert.ToInt32(Console.ReadLine());
        b = Convert.ToInt32(Console.ReadLine());
        stopwatch.Reset();
        stopwatch.Start();
        int res = getGYSByQuick(a, b);
        stopwatch.Stop();
        Console.WriteLine(res + " 用时:" + stopwatch.ElapsedMilliseconds);
    }
}

//更向减损术和移位结合
static int getGYSByQuick(int a, int b) {

    if (a == b) {
        return a;
    }

    if ((a & 1) == 0 && (b & 1) == 0)
    {
        //两个都是偶数
        return getGYSByQuick(a >> 1, b >> 1) << 1;
    }
    else if ((a & 1) == 0 && (b & 1) == 1)
    {
        //a是偶数,b不是
        return getGYSByQuick(a >> 1, b);
    }
    else if ((a & 1) == 1 && (b & 1) == 0)
    {
        //b是偶数,a不是
        return getGYSByQuick(a, b >> 1);
    }
    else {
        //都是奇数,奇数减奇数必为偶
        int mid = 0;
        int min = 0;
        if (a > b)
        {
            mid = a - b;
            min = b;
        }
        else {
            mid = b - a;
            min = a;
        }
        return getGYSByQuick(mid, min);
    }
}


可以看出如果是偶数的话,可以右移一位(除以2),缩小一半的范围

计算什么都是 0ms


首页 我的博客
粤ICP备17103704号