Finding a squence.

May 12, 2007

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.

Posted by raditha at May 12, 2007 10:42 AM
Your Ad Here

 

Jabber  |  Linux  |  mySQL  |  PHP  |  Java  |  Site Map  |  Wiki

Downloads  |  About  |  Links  |  Contact  |  Home

 

Copyright © Raditha Dissanayake 2003 - 2007

Terms of Use  |  Privacy

 

 

May 2007
Sun Mon Tue Wed Thu Fri Sat
    1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31