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 14:27 ID:lpHbmpVF

public class Prog {
    public static void main(String[] args) {
        int top = Integer.parseInt(args[0]);
        int[] m = new int[top+1];
        m[1] = 1;
        for(int i=2; i<=top; i++) {
            long j = i;
            int n = 0;
            do {
                n++;
                if((j&1) == 0) j /= 2;
                else j = j*3 + 1;
            } while(j > i);
            if(j == i) System.err.println("Infinite sequence: "+i);
            else m[i] = n + m[(int)j];
        }
        long max = 0;
        int maxi = -1;
        for(int i=1; i<=top; i++) if(m[i] > max) max = m[maxi = i];
        System.out.println(max+" @ "+maxi);
    }
}


$ time java Prog 1000000
525 @ 837799

real    0m0.389s
user    0m0.328s
sys     0m0.036s

$ time java Prog 10000000
686 @ 8400511

real    0m3.061s
user    0m2.876s
sys     0m0.084s

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