Gets an array of primes up until a num using the sieve Of Atkin method - Java java.lang

Java examples for java.lang:Math Algorithm

Description

Gets an array of primes up until a num using the sieve Of Atkin method

Demo Code


//package com.java2s;

import java.util.*;

public class Main {
    /**/* www.j  a v a2  s.  c  om*/
     * Gets an array of primes up until a num using the sieveOfAtkin method
     *
     * @param num The upper limit
     * @return An array of primes up until <em>num</em>
     */
    public static Integer[] sieveOfAtkin(int num) {
        boolean[] sieve = new boolean[1000 + 1];
        int limitSqrt = (int) Math.sqrt(1000f);
        Arrays.fill(sieve, false);
        sieve[0] = false;
        sieve[1] = false;
        sieve[2] = true;
        sieve[3] = true;

        for (int x = 1; x <= limitSqrt; x++) {
            for (int y = 1; y <= limitSqrt; y++) {
                int n = (4 * x * x) + (y * y);
                if ((n <= 1000) && (n % 12 == 1 || n % 12 == 5)) {
                    sieve[n] = !sieve[n];
                }

                n = (3 * x * x) + (y * y);
                if ((n <= 1000) && (n % 12 == 7)) {
                    sieve[n] = !sieve[n];
                }

                n = (3 * x * x) - (y * y);
                if ((x > y) && (n <= 1000) && (n % 12 == 11)) {
                    sieve[n] = !sieve[n];
                }
            }
        }

        for (int n = 5; n <= limitSqrt; n++) {
            if (sieve[n]) {
                int x = n * n;
                for (int i = x; i <= 1000; i += x) {
                    sieve[i] = false;
                }
            }
        }

        List<Integer> result = new ArrayList<Integer>();
        for (int i = 0; i < sieve.length; i++) {
            if (sieve[i])
                result.add(i);
        }

        return result.toArray(new Integer[0]);
    }
}

Related Tutorials