c# - 计算两个以上值的最大公约数 (GCD)
问题描述
在 VB.NET 或 C# 中,我希望能够动态计算一个或多个值的最大公约数 (GCD),而无需使用递归方法。
我以C# 中的这个解决方案为指导来计算两个值的 GCD。现在,我想调整该解决方案以能够计算不确定数量的值(一个或多个包含在传递给下面函数的值数组中的值)......
这就是我目前所做的:
VB.NET(原代码):
<DebuggerStepperBoundary>
Private Shared Function InternalGetGreatestCommonDivisor(ParamArray values As Integer()) As Integer
' Calculate GCD for 2 or more values...
If (values.Length > 1) Then
Do While Not values.Contains(0)
For Each value As Integer In values
Dim firstMaxValue As Integer = values.Max()
Dim secondMaxValue As Integer = values.OrderByDescending(Function(int As Integer) int)(1)
values(values.ToList.IndexOf(firstMaxValue)) = (firstMaxValue Mod secondMaxValue)
Next value
Loop
Return If(values.Contains(0), values.Max(), values.Min())
Else ' Calculate GCD for a single value...
Return ...
End If
End Function
C#(在线代码转换,我完全没有测试过):
[DebuggerStepperBoundary]
private static int InternalGetGreatestCommonDivisor(params int[] values)
{
// Calculate GCD for 2 or more values...
if (values.Length > 1)
{
while (!values.Contains(0))
{
foreach (int value in values)
{
int firstMaxValue = values.Max();
int secondMaxValue = values.OrderByDescending((int @int) => @int).ElementAtOrDefault(1);
values[values.ToList().IndexOf(firstMaxValue)] = (firstMaxValue % secondMaxValue);
}
}
return (values.Contains(0) ? values.Max() : values.Min());
}
else // Calculate GCD for a single value...
{
return ...;
}
我知道类型转换为 List 会影响大量值的整体性能,但最优先的事情是使该算法按预期工作,最后对其进行优化/重构。
我的适应对某些值组合按预期工作,但对另一些组合不起作用。例如在这个在线 GCD 计算器中,如果我们输入这些值:{1920, 1080, 5000, 1000, 6800, 5555} 理论上 GCD 是 5,或者至少这是那个在线服务计算的 GCD,但是我的算法返回 15。
解决方案
// pass all the values in array and call findGCD function
int findGCD(int arr[], int n)
{
int gcd = arr[0];
for (int i = 1; i < n; i++) {
gcd = getGcd(arr[i], gcd);
}
return gcd;
}
// check for gcd
int getGcd(int x, int y)
{
if (x == 0)
return y;
return gcd(y % x, x);
}
推荐阅读
- angular6 - 检查formarray中的formgrup是否是有效的角度6反应形式
- c++ - 我需要一些关于 .h 文件中的字符串的帮助
- crash - 为什么我的机器人上的数据似乎是随机重置的,没有任何更新或通知?
- python - 使用正则表达式打印提取的子字符串会导致“
" - libcurl - C/C libcurl如何POST表单提交,只是普通的web表单提交数据
- postgresql - postgres 9.3 慢查询
- flutter - 当 TextField 小部件点击或释放时 Flutter 小部件重建
- azure - 连接到 Azure GCC 或 GCC 高云基础架构是否有任何地理限制
- sql - SQL - '不是 GROUP BY 表达式'
- python - 发送 POST 多部分 python