3n+1 给出负数
3n+1 giving negative numbers
最近发现了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();
}
我做错了什么?谢谢!
这是由于 整数溢出 造成的:
In computer programming, an integer overflow occurs when an arithmetic
operation attempts to create a numeric value that is outside of the
range that can be represented with a given number of bits – either
larger than the maximum or lower than the minimum representable value.
您可以使用 64 位整数类型,以获得更大范围的整数。显然在后一种情况下也可以注意到溢出,但它会以非常大的数量发生。使用 64 位整数可以表示
18,446,744,073,709,551,615 numbers
而对于 32 位整数,您可以表示
4,294,967,295 numbers
在 Int32
和 Int64
的情况下,您应该将上述数字除以二并取商,这将是 最大正数 可以表示。应该这样做,因为 Int32
和 Int64
都是有符号整数。
更好的方法是使用 UInt64
,参见 here,它可用于表示值范围为 0 到 18,446,744,073,709,551,615 的无符号整数。
在这种情况下肯定也会注意到溢出。
int
最大 2,147,483,647
。 3n
当 n
为 999,999,999
时会变大并溢出,这将导致 n
在 n = 3 * n + 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();
}
我做错了什么?谢谢!
这是由于 整数溢出 造成的:
In computer programming, an integer overflow occurs when an arithmetic operation attempts to create a numeric value that is outside of the range that can be represented with a given number of bits – either larger than the maximum or lower than the minimum representable value.
您可以使用 64 位整数类型,以获得更大范围的整数。显然在后一种情况下也可以注意到溢出,但它会以非常大的数量发生。使用 64 位整数可以表示
18,446,744,073,709,551,615 numbers
而对于 32 位整数,您可以表示
4,294,967,295 numbers
在 Int32
和 Int64
的情况下,您应该将上述数字除以二并取商,这将是 最大正数 可以表示。应该这样做,因为 Int32
和 Int64
都是有符号整数。
更好的方法是使用 UInt64
,参见 here,它可用于表示值范围为 0 到 18,446,744,073,709,551,615 的无符号整数。
在这种情况下肯定也会注意到溢出。
int
最大 2,147,483,647
。 3n
当 n
为 999,999,999
时会变大并溢出,这将导致 n
在 n = 3 * n + 1;