我正在嘗試為 N 個號碼找到 GRC。例如 N = 4,所以 4 個數字例如是 199 199 -199 -199。我得到這些數字的 StackOverflowException 。為什么?第一個輸入我應該找到 GRC 的整數個數。第二個輸入數字是寫在一行中的數字陣列,由“”分隔。這是我的代碼:
static int GCD(int a, int b)
{
if (b == 0) return a;
if (a > b) return GCD(b, a - b);
else return GCD(a, b-a);
}
static void Main()
{
var input = Convert.ToInt32(Console.ReadLine());
int gcd;
string readLine = Console.ReadLine();
string[] stringArray = readLine.Split(' ');
int[] intArray = new int[input];
for (int i = 0; i < stringArray.Length; i )
{
intArray[i] = int.Parse(stringArray[i]);
}
if (input >= 2)
{
gcd= Math.Abs(GCD(intArray[0], intArray[1]));
}
else
{
gcd= intArray[0];
}
for (int i = 2; i < input; i )
{
gcd= Math.Abs(GCD(gcd, intArray[i]));
}
Console.WriteLine(Math.Abs(gcd));
Console.ReadKey();
}
有什么建議可以改進代碼嗎?
uj5u.com熱心網友回復:
首先,不清楚是什么GRC。您的代碼是關于GCD- G retest C ommon Divisor。讓我們改進它的實作。
如果你有很大的不同,那么你將會有遞回呼叫a并有Stack Overflow Exception。ba = 1_000_000_000b = 1~ a - b ~ 1_000_000_000GCD
讓我們改用模運算:如果a = b b ... b remainder,我們可以一次性找到余數,而無需減去b:remainder = a % b
代碼:
static int GCD(int a, int b)
{
a = Math.Abs(a);
b = Math.Abs(b);
if (a == 0)
return b; // b divides both 0 and itself
if (b == 0)
return a; // a divides both 0 and itself
if (a % b == 0) // b divides both a and b, so b is GCD(a, b)
return b;
return GCD(b, a % b);
}
然后我們可以計算任意GCD數量的數字
static int GCD(IEnumerable<int> numbers) {
if (numbers is null)
throw new ArgumentNullException(nameof(numbers));
int result = 0;
foreach (var number in numbers)
if (result == 0)
result = number;
else
result = GCD(result, number);
return result != 0
? result
: throw new ArgumentOutOfRangeException(nameof(numbers), "Empty sequence");
}
用法:(小提琴)
using System.Linq;
...
static void Main() {
int gcd = GCD(Console
.ReadLine()
.Split(' ', StringSplitOptions.RemoveEmptyEntries)
.Select(item => int.Parse(item)));
Console.Write(gcd);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/514855.html
標籤:C#算法欧几里得算法
下一篇:如何取出或更改類陣列物件的鍵名?
