Pages

Tuesday, September 8, 2009

Euler Problem 14 solution

Time (s): ~0.355
package margusmartseppcode.From_10_to_19;

public class Problem_14 {
 static final int maxSize = 1000000;
 static long d[] = new long[maxSize];
 static {
  d[1] = 1;
 }

 static long makeChain(long nr) {
  if (nr >= maxSize)
   return makeChain(nr % 2 == 0 ? nr / 2 : 3 * nr + 1) + 1;
  else if (d[(int) nr] == 0)
   d[(int) nr] = makeChain(nr % 2 == 0 ? nr / 2 : 3 * nr + 1) + 1;

  return d[(int) nr];
 }

 public static void main(String[] args) {
  int maxNr = 0;
  long maxLen = 0;

  for (int i = 1; i < 1000000; i++) {
   if (makeChain(i) > maxLen) {
    maxNr = i;
    maxLen = d[i];
   }
  }

  System.out.println(maxNr);
 }
}

No comments:

Post a Comment