计算最大公约数-更相减损术
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 = getGYSByXJF2(a, b);
        stopwatch.Stop();
        Console.WriteLine(res + " 用时:" + stopwatch.ElapsedMilliseconds);
    }
}

//相减法--递归的方式别用,999999和1?栈会崩的。
static int getGYSByXJF(int a, int b) {
    if (a == b) {
        return a;
    }
    if (a > b)
    {
        return getGYSByXJF(a - b, b);
    }
    else {
        return getGYSByXJF(b - a, a);
    }
}

//相减法 不用递归
static int getGYSByXJF2(int a, int b)
{

    while (a != b) {
        if (a > b)
        {
            a = a - b;
        }
        else {
            b = b - a;
        }
    }

    return a;
}


思路是大数和小数相加得差,如果这个差和小数不相等,那么这个小数和差的最大公约数就是大数和小数的最大公约数

计算99999999和88888888,时间为0ms

但是如果计算99999999和1,时间为296ms(这就和穷举法差不多了)


首页 我的博客
粤ICP备17103704号