title: Project Euler 14(Collatz Conjecture), issue implementing cache in Java
body: <p>I was solving Project Euler problems and I'm stuck at number 14, I did manage to solve it using brute force, the problem states:
  <a href="http://projecteuler.net/problem=14" rel="nofollow noreferrer">http://projecteuler.net/problem=14</a></p>
  <blockquote>
  <p>The following iterative sequence is defined for the set of positive integers:</p>
  <pre><code>   n → n/2 (n is even)
     n → 3n + 1 (n is odd)
  </code></pre>
  <p>Using the rule above and starting with 13, we generate the following sequence:</p>
  <pre><code>   13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
  </code></pre>
  <p>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.</p>
  <p>Which starting number, under one million, produces the longest chain?</p>
  <p>NOTE: Once the chain starts the terms are allowed to go above one million.</p>
  </blockquote>
  <p>What I want to do is to implement a cache, I want to use an integer array as the cache, the index will be the number and the count stored in each cell will be the length of the chain, when we hit a number for which the cache cell already has a positive number we skip further checking(break the loop), fetch the existing counter data from the loop and add it to the current counter value, and start from the next number, so here's the implementation:</p>
  <p><strong>Working brute force code removed due to Project Euler policy, down below is the faulty code.</strong></p>
  <pre><code>public class Challenge14 {
  
  public static void main(String[] args) {
      
      int[] collatzCache=new int[1000000]; //cache
      
      int count=0;
      long maxCount=0;
      int maxNumber=0;
      long number;
      
      int limit=1000000;
      
      for(int i=0;i&lt;limit;i++)
      {
          int counter=0;
          number=i;
          while(number&gt;1)
          {
              if(number%2==0)
              {
                  number=number/2;
              }
              else 
              {
                  number=3*number+1;
              }
  
              if(number&lt;limit &amp;&amp; collatzCache[(int)number]&gt;0) //check
              {
                  counter=collatzCache[(int) number];
                  break;
              }
              counter++;
          }
          count=counter+1;
          collatzCache[i]=count;
      if(count&gt;maxCount)
      {
          maxCount=count;
          maxNumber=i;
      }
      }
      System.out.println(maxNumber);
  
  
  }
  }
  </code></pre>
  <p>But it's not working, where am I going wrong here? Is it due to the long to int typecasting?</p>