Skip to content

Instantly share code, notes, and snippets.

@bencoveney
Created July 17, 2014 12:23
Show Gist options
  • Save bencoveney/ffc34dbc010f58d5d263 to your computer and use it in GitHub Desktop.
Save bencoveney/ffc34dbc010f58d5d263 to your computer and use it in GitHub Desktop.
Longest Collatz sequence
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;
using System.Threading.Tasks;
namespace EulerProject
{
class Program
{
private static Dictionary<long, long> CollatzLengths;
[STAThread]
static void Main(string[] args)
{
CollatzLengths = new Dictionary<long, long>();
long highestLength = 0;
for (long i = 1; i < 1000000; i++)
{
Console.WriteLine(i);
Console.CursorTop--;
long length = findCollatzLength(i);
if(length > highestLength)
{
highestLength = length;
Console.WriteLine("Highest Length is now {0} for {1}", highestLength, i);
}
}
Console.ReadLine();
}
public static long findCollatzLength(long number)
{
long amount = 0;
while(number != 1)
{
if(CollatzLengths.ContainsKey(number))
{
return amount + CollatzLengths[number];
}
else
{
amount++;
if (number % 2 == 0)
{
number = number / 2;
}
else
{
number = (3 * number) + 1;
}
}
}
return amount;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment