Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

/prog/ Challenge

Name: Anonymous 2007-09-04 15:06 ID:bG0CVxDp

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: Anonymous 2007-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;

    for (int n=1; n<=UpperLimit; n++)
    {
      CurrentSequenceLength = calculateSequenceLength(n);
      LongestSequenceLength = Math.max(LongestSequenceLength, CurrentSequenceLength);
    }
       
    System.out.println("Longest sequence for numbers up to " + UpperLimit + " is " +

LongestSequenceLength);

  }

}


And the output:

Longest sequence for numbers up to 1000000 is 525

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List