Skip to content

Instantly share code, notes, and snippets.

@fabiomaulo
Created November 5, 2022 23:04
Show Gist options
  • Save fabiomaulo/ea2577261f8d4c29b6de2ae2fd0ab060 to your computer and use it in GitHub Desktop.
Save fabiomaulo/ea2577261f8d4c29b6de2ae2fd0ab060 to your computer and use it in GitHub Desktop.
The famous 3X + 1
internal class Program
{
private const ulong limit = 1;
private static void Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("No start number specified");
return;
}
if (!ulong.TryParse(args[0], out ulong inputNumber))
{
Console.WriteLine("No valid start number: {0}", args[0]);
return;
}
ulong iterations = 0;
ulong maxvalue = inputNumber;
ulong actual = inputNumber;
while (actual > limit)
{
iterations++;
if ((actual & limit) == limit)
{
actual *= 3;
actual++;
}
else
{
actual >>= 1;
}
maxvalue = Math.Max(actual, maxvalue);
}
Console.WriteLine("{0} solved in {1} iterations", inputNumber, iterations);
Console.WriteLine("Max value riched was {0}.", maxvalue);
}
}
@fabiomaulo
Copy link
Author

using System.Numerics;

internal class Program
{
	private static void Main(string[] args)
	{
		if (args.Length < 1)
		{
			Console.WriteLine("No start number specified");
			return;
		}
		if (!BigInteger.TryParse(args[0], out BigInteger inputNumber))
		{
			Console.WriteLine("No valid start number: {0}", args[0]);
			return;
		}
		BigInteger limit = 1;
		BigInteger iterations = 0;
		BigInteger maxvalue = inputNumber;
		BigInteger actual = inputNumber;
		while (actual > limit)
		{
			iterations++;
			if ((actual & limit) == limit)
			{
				actual *= 3;
				actual++;
			}
			else
			{
				actual >>= 1;
			}
			maxvalue = BigInteger.Max(actual, maxvalue);
		}
		Console.WriteLine("{0} solved in {1} iterations", inputNumber, iterations);
		Console.WriteLine("Max value riched was {0}.", maxvalue);
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment