Longest Collatz sequence

Problem 14 Project Euler 

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
public class Solution 
	{
    static void Main(String[] args) 
    {
        /* Enter your code here. Read input from STDIN. 
        Print output to STDOUT. Your class should be named Solution */          
        var t = Convert.ToInt32(Console.ReadLine());
        for(long i=0; i< t; i++)
            Console.WriteLine(CountFunction(Convert.ToInt32(Console.ReadLine())));
    }
    static long CountFunction(long n)
    {
        long i =1;
        var count =new long[2];
        while(i++< n)
        {
            var temp = NumberAndFrequency(i);
            if(temp>=count[0])
            {
                count[0]=temp;
                count[1]=i;
            }
        }
        return count[1];
    }
    
    static long NumberAndFrequency(long n)
    { 
        var count=0;
        while(n!=1)
        {
            count++;
            if(n%2==0)
                n/=2;
            else
                n = 3*n +1;
        }
        return count;
    }
}

Comments

Popular Posts