Hey, I've stolen this challenge from some website, it's pretty easy but I know most of you will fuck it up.
A sequence is defined by:
n -> n/2 (n is even)
n -> 3n + 1 (n is odd)
Find the longest sequence, with a starting number under one million.
Bonus points when you find the solution for ten million.
Name:
Anonymous2007-09-05 7:37 ID:N3V2WcCD
I haven't written anything in Java for over five years, but I wanted to use the arbitrary precision integer library. I forgot how disgustingly verbose it is.
I assumed that the only cycle present is 1 -> 2 -> 4, and special cased those three starting positions to 3 (though I needn't have done so for 4). Everything else therefore must terminate at 1.
Well, here is the code anyway:
import java.math.BigInteger;
public class World4ChProgPuzzle {
private static int calculateSequenceLength(int start)
{
switch(start)
{
case 1:
case 2:
case 4:
return 3;
default:
{
int Length = 1;
BigInteger n = BigInteger.valueOf(start);
while (!n.equals(BigInteger.ONE))
{
if (n.mod(BigInteger.valueOf(2)).equals(BigInteger.ZERO))
{
n = n.divide(BigInteger.valueOf(2));
}
else
{
n = n.multiply(BigInteger.valueOf(3)).add(BigInteger.valueOf(1));
}
++Length;
}
return Length;
}
}
}
public static void main(String[] args)
{
int UpperLimit = 1000000;
int LongestSequenceLength = 0;
int CurrentSequenceLength;