Eratosthenes.mj 1.59 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
class Eratosthenes {
    
    /**
     * @param max a positive integer.
     * @returns a sorted array of all prime numbers between 1 and max (exclusive).
     */
    public int[] primes(int max) {
        boolean[] sieve = new boolean[max];
        int count = 0;
        
        /* Initialize array. */
        {
            sieve[0] = false;
            sieve[1] = false;
            int i = 2;
            while (i < max) {
                sieve[i] = true;
                i = i + 1;
            }
        }
        
        /* Sieve of Eratosthenes algorithm. */
        {
            int prime = 2;
            while (prime < max) {
                if (sieve[prime]) {
                    count = count + 1;
                    
                    /* Deliberately unoptimized (strength reduction is possible). */
                    int mult = prime;
                    while (prime * mult < max) {
                        sieve[prime * mult] = false;
                        mult = mult + 1;
                    }
                }
		
                prime = prime + 1;
            }
        }
        
        int[] result = new int[count];
        {
            int i = 0;
            int j = 0;
            while (i < max) {
                if (sieve[i]) {
                    result[j] = sieve[i];
                    j = j + 1;
                }
                
                i = i + 1;
            }
        }
        
        return result;
    }
    
    public static void main(String[] args) {
        Eratosthenes e = new Eratosthenes();
        int num = System.in.read();
        e.sieve(num);
    }
}