Get all prime numbers below n - Java java.lang

Java examples for java.lang:int prime

Description

Get all prime numbers below n

Demo Code


//package com.java2s;

import java.util.ArrayList;

public class Main {
    /**/*from w  w w .j  av a  2 s.c  o m*/
     * Get all prime numbers below n
     * @param n the number to get the primes below
     * @return an array list of all the prime number below n
     */
    public static ArrayList<Integer> getAllPrimesBelow(int n) {
        if (n <= 2) {
            return new ArrayList<Integer>();
        }
        boolean[] is_composite = new boolean[(n) >> 1];
        ArrayList<Integer> results = new ArrayList<Integer>(
                (int) Math.ceil(1.25506 * n / Math.log(n)));
        results.add(2);
        for (int i = 1; i < is_composite.length; i++) {
            if (!is_composite[i]) {
                int cur = (i * 2) + 1;
                results.add(cur);
                for (int j = i + cur; j < is_composite.length; j += cur) {
                    is_composite[j] = true;
                }
            }
        }
        return results;
    }
}

Related Tutorials