[C#] Find the greatest common divisor

Example 1: Find the greatest common divisor of 100 and 44:

100 % 44 = 12 (dividing 100 by 44 leaves 12)

44 % 12 = 8

12 % 8 = 4

8 % 4 = 0 (final remainder 0)

So 4 is the greatest common divisor of 100 and 44

Example 2: Find the greatest common divisor of 100 and 17:

100 % 17 = 15

17 % 15 = 2

15 % 2 = 1 (last remainder 1)

So 100 and 17 have no greatest common divisor

Summarize:

Code: Find the greatest common divisor of n and m (n>m)

while (k > 1)
{
    k = n % m;
    if (k == 0)
    {
        Console.WriteLine("最大公约数是" + m );
    }
    if (k == 1)
    {
        Console.WriteLine("无最大公约数" );
    }
    n = m;
    m = k;
}

Guess you like

Origin blog.csdn.net/weixin_61427881/article/details/127969452