|
/*
Version that eliminates the multiplication by 3.
*/
using System;
using System.Diagnostics;
namespace program_to_optimize
{
class Program
{
//current maximum cycle length
private static int MaxCycleCount = 0;
//first number
private const int FirstNumber = 1;
//second number
private const int SecondNumber = 1000000;
//function used to solve the problem
static void Solve()
{
//for every number between the first and the last
for (int i = FirstNumber; i < SecondNumber; ++i)
{
//cycle count of current number
int iCurrentCycleCount = 1;
//current number
long iNumberToTest = i;
//while the current number is not 1
while (iNumberToTest != 1)
{
//test if the number is odd
if ((iNumberToTest & 0x1) == 1)
{
//the number is odd
iNumberToTest = iNumberToTest + iNumberToTest + iNumberToTest + 1;
}
else
{
//the number is even
iNumberToTest = iNumberToTest >> 1;
}
//increment cycle count of current number
iCurrentCycleCount++;
}
//if current number's cycle count is greater than the maximum cycle count, set maximum cycle count to current number's cycle count
if (iCurrentCycleCount > MaxCycleCount)
{
MaxCycleCount = iCurrentCycleCount;
}
}
}
//main function
static void Main(string[] args)
{
//use a stopwatch to measure execution time
Stopwatch tmrExecutionTime = new Stopwatch();
//start measurement
tmrExecutionTime.Start();
//solve the problem
Solve();
//stop measurement
tmrExecutionTime.Stop();
//print result and time
Console.WriteLine("{0} {1}", MaxCycleCount, tmrExecutionTime.ElapsedMilliseconds);
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.