14. Sequence of Triangle Numbers

The following iterative sequence is defined for the set of positive integers:

n → n/2 (n is even)
n → 3n + 1 (n is odd)

Using the rule above and starting with 13, we generate the following sequence:

13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1

It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.

Which starting number, under one million, produces the longest chain?

NOTE: Once the chain starts the terms are allowed to go above one million.

import java.util.Arrays;
public class Problem14 {
    public void iterative() {
       long maxcount = 0, maxnumber = 1;
       int evalue = 1000000;
       long chain[] = new long[1000000];
       boolean usedChain[] = new boolean[chain.length];
       Arrays.fill(usedChain, false);
       chain[1]=1;
       chain[2]=2;
       usedChain[1]=true;
       usedChain[2]=true;
       for (int i=1819;i<evalue;i++) {
              //int i =1819;
           long k =i, count=1;
           while (k>1) {
               count++;
               if (k%2==0)
                   k=k/2;
               else
                   k=3*k+1;

               if (k<1000000) {
                   if (usedChain[(int) k]) {
                       count = count+chain[(int) k]-1;
                       break;
                   }
               }
           }
           if (count>maxcount) {
               maxcount = count;
               maxnumber = i;
           }
           chain[i]=count;
       }
       System.out.println(maxnumber);
    }
  public static void main(String[] args) {
        Problem14 p = new Problem14();
        p.iterative();
    }
}
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: