Run Code  | API  | Code Wall  | Misc  | Feedback  | Login  | Theme  | Privacy  | Patreon 

project euler 14, C#

//Title of this code
//Rextester.Program.Main is the entry point for your code. Don't change it.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Rextester
{
    public class Program
    {
        static int[] cache = new int[1000000];
        public static void Main(string[] args)
        {            
            int max=0;
            int res=0;
            for(int i=1; i<1000000; i++)
            {
                int l = GetChainLength(i);
                if(l>max)
                {
                    max = l;
                    res = i;
                }
            }
            Console.WriteLine(res);
        }
        
        static int GetChainLength(int number)
        {
            if(number == 1)
            {
                cache[1]=1;
                return 1;
            }
            long next = number;
            int count=0;
            while(next >= number)
            {
                if(next%2 == 0)
                {
                    next = next/2;
                }
                else
                {
                    next = 3*next+1;
                }
                count++;
            }
            cache[number] = count+cache[next];
            return cache[number];            
        }
    }
}
 run  | edit  | history  | help 0