• Finding a squence.

    Problem #14 at project euler is straightforward. You need to find an iterative sequence or rather the starting number that results in the most terms. If you are a strict mathematician the problem description isn’t very sound but anyway here is the solution:

    public void problem14()
    {
    int n0;
    long n;
    int maxTerms=0, terms=0, nMax=0;
    int results[] = new int[1000002];
    
    for(n0=5 ; n0 < 1000000 ; n0++, terms=0)
    {
    n = n0;
    do {
    if(n % 2 == 0)
    {
    n = n/2;
    }
    else
    {
    n = 3*n + 1;
    }
    terms++;
    //System.out.print(n +",");
    if(n < n0)
    {
    if(n < 0)
    {
    System.out.println("N =" + n +" for n0="+n0);
    break;
    }
    if(results[(int)n] != 0)
    {
    terms += results[(int)n];
    break;
    }
    }
    }while(n != 1);
    
    results[n0] = terms;
    if(maxTerms < terms)
    {
    maxTerms = terms;
    nMax = n0;
    }
    //System.out.println("");
    }
    System.out.println(nMax +" gives the most terms" + maxTerms);
    }

    At first I used integers instead of longss and ran into a situation where some of the terms exceeded 2^32 -1 which lead to array out of bounds exceptions. Switching to longs solved that one easily.

    Saturday, May 12th, 2007 at 10:42
No comments yet.

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
TOP