title: Create an efficient way to sum
body: <p>i have wrote a code to calculate the sum of the lengths whereby</p>
  
  <p><code>syra(1) = 1</code></p>
  
  <p><code>syra(2) = n + syra(n/2) if n%2==0</code></p>
  
  <p><code>syra(3) = n + (n*3) + 1</code></p>
  
  <p>eg.</p>
  
  <ul>
  <li>syra(1) will generate 1</li>
  <li>syra(2) will generate 2 1</li>
  <li>syra(3) will generate 3 10 5 16 8 4 2 1</li>
  <li>lengths(3) will be sum of all syra(1),syra(2),syra(3) which is 11.</li>
  </ul>
  
  <p>Here's the code :</p>
  
  <pre><code>public static int lengths(int n) throws IllegalArgumentException{
    int syra = n;
    int count = 0;    
    int sum = 0;
    if (syra &lt; 1){
      throw new IllegalArgumentException("Value must be greater than 0");
    }else{
      for (int i=1; i&lt;=syra; i++){
        count = i;
        sum++;
        while (count &gt; 1){
          if ((count % 2) == 0){
            count = count / 2;
            sum++;
          }else{
            count = (count * 3) + 1;
            sum++;
          }
        } 
      }   
    }
    return sum;
  }
  </code></pre>
  
  <p>Question is, if i blast the lengths with big value eg 700000, it will take very long time and do repeat step for those syra(10),syra(5)...which already appear in syra(3). </p>
  
  <p>How can I fine tune the code to store some temp (array) of the overlap sequences? </p>
  
  <p>Ok, according to the info, here's my another modified code with array, why it produce array index out of bound error? </p>
  
  <pre><code>public class SyraLengths{
  
  public static void main (String[]args){
      lengths(3);
  }
  
  public static int lengths(int n) throws IllegalArgumentException{
      int syra = n;
      int count = 0;  
      int sum = 0;
      int [] array = new int [syra+1];
      array[0] = 0;
      if (syra &lt; 1){
          throw new IllegalArgumentException("Value must be greater than 0");
          }else{
  
  
                  for (int i=1; i&lt;=syra; i++){
                      count = i;
                      sum++;
  
                      while (count &gt; 1){
  
                          if(array[count] !=0){sum = sum + array[count];}
  
                          else if ((count % 2) == 0){
                              count = count / 2;
                              array[count]=sum;
                              sum++;
                          }else{
                              count = (count * 3) + 1;
                              array[count]=sum;
                              sum++;
  
                              }
                          } 
                  }   
              }return sum;
  }
  </code></pre>
  
  <p>}</p>