【发布时间】:2021-11-02 22:57:07
【问题描述】:
我有一个任务,这让我有点头疼。目标是找到三个整数的最大公约数,我成功地用两个相当容易地做到了,但是当我不能使用任何数组时,它会变得有点复杂。
这是我使用的完整代码,从两个整数中找到 gcd,测试全部为绿色:
public static int GetGcdByEuclidean(int a, int b)
{
if (a == 0 && b == 0)
{
throw new ArgumentException(null);
}
else if (a == int.MinValue)
{
throw new ArgumentOutOfRangeException(nameof(a));
}
else if (b == int.MinValue)
{
throw new ArgumentOutOfRangeException(nameof(b));
}
else
{
int abs1 = Math.Abs(a);
int abs2 = Math.Abs(b);
a = abs1;
b = abs2;
while (a != 0 && b != 0)
{
if (a > b)
{
a %= b;
}
else
{
b %= a;
}
}
return a | b;
}
}
现在我对 GCD 使用了相同的原理,但使用了我在网上找到的东西:gcd(a, b, c) = gcd(a, gcd(b, c)) = gcd( gcd(a, b), c) = gcd(gcd(a, c), b)..
public static int GetGcdByEuclidean(int a, int b, int c)
{
int result = 0;
if ((a == 0 && b == 0) && c == 0)
{
throw new ArgumentException(null);
}
else if (a == int.MinValue)
{
throw new ArgumentOutOfRangeException(nameof(a));
}
else if (b == int.MinValue)
{
throw new ArgumentOutOfRangeException(nameof(b));
}
else if (c == int.MinValue)
{
throw new ArgumentOutOfRangeException(nameof(c));
}
else
{
int abs1 = Math.Abs(a);
int abs2 = Math.Abs(b);
int abs3 = Math.Abs(c);
a = abs1;
b = abs2;
c = abs3;
while (a != 0 && b != 0 && c != 0)
{
if (a > b && a > c && b > c)
{
b %= c;
a %= b;
result = a;
}
else if (a > b && a > c && b < c)
{
c %= b;
a %= c;
result = a;
}
else if (b > a && b > c && a > c)
{
a %= c;
b %= a;
result = b;
}
else if (b > a && b > c && a < c)
{
c %= a;
b %= c;
result = b;
}
else if (c > a && c > b && a > b)
{
a %= b;
c %= a;
result = c;
}
else
{
b %= a;
c %= b;
result = c;
}
}
return result;
}
}
【问题讨论】:
-
这更像是一个基于数学的问题,而不是纯粹的编程问题。这里有一些答案:math.stackexchange.com/questions/93731/…
标签: c# if-statement while-loop greatest-common-divisor