我最近發現了關於3n + 1的問題,並想寫一個簡單的代碼來解決這個問題。3n + 1給出負數
這一切都有效,但在高的奇數如999,999,999它去負數,並重復一個無休止的循環,我不知道爲什麼。
// if n is odd n = 3n+1
// if n is even n = n/2
while (true)
{
int n;
Console.WriteLine("Enter a positive whole number greater than one: ");
while (!Int32.TryParse(Console.ReadLine(), out n))
{
Console.WriteLine("Enter a positive whole number greater than one: ");
}
while (n != 1)
{
if (n % 2 == 0)
{
n /= 2;
Console.WriteLine("n/2 = " + n);
}
else
{
n = 3 * n + 1;
Console.WriteLine("3 * n + 1 = " + n);
}
}
Console.ReadLine();
Console.Clear();
}
我在做什麼錯?謝謝!
聽起來像之後你正在運行到[整數溢出](https://en.wikipedia.org/wiki/Integer_overflow) –
[collatz conjeture](https://en.wikipedia.org/wiki/Collatz_conjecture)已被檢查所有小於87×2^60的數字(通過yoyo @ home項目) - 您需要的整數大於[66 (https://www.wolframalpha.com/input/?i=ln_2(87%C3%972%5E60))進行競爭。 int32和int64太小。使用[十進制](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/decimal)([10^28〜> 2^93](https://www.wolframalpha .com/input /?i = ln_2(10%5E28)))或[BigInteger](https://msdn.microsoft.com/en-us/library/system.numerics.biginteger(v = vs.110)。 ASPX)。編輯:忽略運行時間。 – Theraot