Note that there are some explanatory texts on larger screens.

plurals
  1. POSieve of Atkin returns array... with invalid indices - Java
    primarykey
    data
    text
    <p>So I made a <a href="http://en.wikipedia.org/wiki/Sieve_of_Atkin" rel="nofollow">sieve of Atkin</a> algorithm to generate primes (for Project Euler problems). It returns an array of primes (int[]) called <code>primes</code>. Problem is, whenever I try accessing that array from some index (I do so in my <code>main</code> method), it throws me a <code>java.lang.ArrayIndexOutOfBounds</code> exception. Help please (and if you think my logic is away with the fairies and there is a simpler way to do this, please tell me)!</p> <pre><code>import java.lang.*; import java.util.*; public class SieveOfAtkin { public static void main(String[] stuff) { int limit = getInt("Limit?"); int[] p = getPrimes(limit); for(int i = 0; i &lt; p.length; i++) { System.out.println(p[i]); } } public static int[] getPrimes(int limit) { boolean[] isPrime = new boolean[limit + 1]; double sqrt = Math.sqrt(limit); int n = 0; for(int i = 0; i &lt; limit + 1; i++) { isPrime[i] = false; } for(int x = 0; x &lt; sqrt; x++) { for(int y = 0; y &lt; sqrt; y++) { n = 4 * x * x + y * y; if(n &lt;= limit &amp;&amp; (n % 12 == 1 || n % 12 == 5)) { isPrime[n] = !isPrime[n]; } n = 3 * x * x + y * y; if(n &lt;= limit &amp;&amp; n % 12 == 7) { isPrime[n] = !isPrime[n]; } n = 3 * x * x - y * y; if(n &lt;= limit &amp;&amp; n % 12 == 11 &amp;&amp; x &gt; y) { isPrime[n] = !isPrime[n]; } } } for(int i = 5; i &lt; sqrt; i++) { if(isPrime[i]) { for(int j = i * i; j &lt; limit; j = j + (i * i)) { isPrime[j] = false; } } } int count = 0; for(int i = 0; i &lt; isPrime.length; i++) { if(isPrime[i]) { count++; } } int[] primes = new int[count]; int found = 0; if (limit &gt; 2) { primes[found++] = 2; } if (limit &gt; 3) { primes[found++] = 3; } for (int p = 5; p &lt;= limit; p += 2) { if (isPrime[p]) { primes[found++] = p; } } return primes; } public static int getInt(String prompt) { System.out.print(prompt + " "); int integer = input.nextInt(); input.nextLine(); return integer; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload