I recently found out about the 3n+1 problem and wanted to write a simple code to do the problem.
It all works but at high odd numbers such as 999,999,999 it goes to negative numbers and repeats an endless cycle and I have no clue why.
// 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();
}
What am I doing wrong? Thanks!