C# 如何计算三个数之间的最大公约数
我必须编写一个程序,使用欧几里德算法用三个数字计算gcd 我已经用两个数字写了这个程序,效果很好,但是我不知道如何用三个数字来写 (最大的问题是它应该是欧几里德算法)C# 如何计算三个数之间的最大公约数,c#,math,numbers,C#,Math,Numbers,我必须编写一个程序,使用欧几里德算法用三个数字计算gcd 我已经用两个数字写了这个程序,效果很好,但是我不知道如何用三个数字来写 (最大的问题是它应该是欧几里德算法) 您可以编写一个从2个数字中获取GCD的方法,在使用2个数字调用它之后,继续使用该结果和下一个数字调用它,直到没有更多的数字 例如,我们可以编写一个方法来获取两个数字的GCD(借用自): 然后,我们可以编写另一个方法,该方法接受一个可变数量的int参数(使用数组),它获取前两个数字的结果,然后通过将该值与下一个数字一起传递给我们的G
您可以编写一个从2个数字中获取GCD的方法,在使用2个数字调用它之后,继续使用该结果和下一个数字调用它,直到没有更多的数字 例如,我们可以编写一个方法来获取两个数字的GCD(借用自): 然后,我们可以编写另一个方法,该方法接受一个可变数量的
int
参数(使用数组),它获取前两个数字的结果,然后通过将该值与下一个数字一起传递给我们的GCD方法来继续更新该值:
public static int GCD(params int[] numbers)
{
// Do some argument validation and return 0 or throw an exception
if (numbers == null || numbers.Length == 0) return 0;
// Start with the result being just the first number
var result = numbers[0];
// Then get the GCD of the result and the next number
// and store that back in the result variable
for(int i = 1; i < numbers.Length;i++)
{
result = GCD(result, numbers[i]);
}
return result;
}
获取前两个数字的GCD,然后获取第三个数字的GCD。嘿,我已经尝试了,但是如果两个第一个数字相同,则会出现错误,因为代码r=z1%z2;剩下的是0!如果除数为零,则应返回股息,您需要执行此检查以避免被零除。
public static int GCD(int first, int second)
{
while (first != 0 && second != 0)
{
if (first > second) first %= second;
else second %= first;
}
return first == 0 ? second : first;
}
public static int GCD(params int[] numbers)
{
// Do some argument validation and return 0 or throw an exception
if (numbers == null || numbers.Length == 0) return 0;
// Start with the result being just the first number
var result = numbers[0];
// Then get the GCD of the result and the next number
// and store that back in the result variable
for(int i = 1; i < numbers.Length;i++)
{
result = GCD(result, numbers[i]);
}
return result;
}
Console.WriteLine(GCD(9, 18, 27)); // Output: 9
Console.WriteLine(GCD(4, 8)); // Output: 4
Console.WriteLine(GCD(25, 15, 100, 30, 9000)); // Output: 5