title: Find the prime-->sieve way
body: <p>I tried it several times but still gives me ArrayOutOfIndex. But i want to save the memory so i use </p>
  
  <pre><code>boolean[]isPrime = new boolean [N/2+1];
  </code></pre>
  
  <p>instead of </p>
  
  <pre><code>boolean[]isPrime = new boolean [N+1];
  </code></pre>
  
  <p>This gives me ArrayOutOfIndex for line 23 and 47</p>
  
  <p>line 23:</p>
  
  <pre><code>    for (int i = 3; i &lt;= N; i=i+2) {
      isPrime[i] = true;
      }
  </code></pre>
  
  <p>line 47:   </p>
  
  <pre><code>  for (int i = 3; i &lt;= N; i=i+2) {
          if (isPrime[i]) primes++;
    ...
     }
  </code></pre>
  
  <hr>
  
  <pre><code>Full code:
  
  public class PrimeSieve {
      public static void main(String[] args) { 
  
          if (args.length &lt; 1) {
              System.out.println("Usage: java PrimeSieve N [-s(ilent)]");
              System.exit(0);
          }
  
          int N = Integer.parseInt(args[0]);
  
          // initially assume all odd integers are prime
  
          boolean[]isPrime = new boolean [N/2+1];
  
          isPrime[2] = true;
  
          for (int i = 3; i &lt;= N; i=i+2) {
              isPrime[i] = true;
          }
  
          int tripCount = 0;
  
          // mark non-primes &lt;= N using Sieve of Eratosthenes
          for (int i = 3; i * i &lt;= N; i=i+2) {
  
              // if i is prime, then mark multiples of i as nonprime
          if (isPrime[i]) {
            int j = i * i;
            while (j &lt;= N){
              tripCount++;
              isPrime[j] = false;
              j = j + 2*i;
              }
                          }
                                              }
  
          System.out.println("Number of times in the inner loop: " + tripCount);
  
          // count and display primes
          int primes = 0;
          if(N &gt;= 2 ){
              primes = 1;
          }
          for (int i = 3; i &lt;= N; i=i+2) {
              if (isPrime[i]) primes++;
              if (args.length == 2 &amp;&amp; args[1].equals("-s"))
                  ; // do nothing
              else
                  System.out.print(i + " ");
          }
          System.out.println("The number of primes &lt;= " + N + " is " + primes);
      }
  }
  </code></pre>