Primes

From programming_contest
Revision as of 04:02, 16 February 2015 by imported>Kmk21 (Created page with "=Sieve of Eratosthenes= <syntaxhighlight line lang="java"> /** * Sieve of Eratosthenes, returns all primes<=n * @param n the maximum prime you want * @return int[] of prime...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Sieve of Eratosthenes

/**
 * Sieve of Eratosthenes, returns all primes<=n
 * @param n the maximum prime you want
 * @return int[] of primes
 */
public ArrayList<Integer> findPrimes( int n ){
	boolean[] a = new boolean[n+1];
	ArrayList<Integer> temp=new ArrayList<Integer>();
	for( int i = 2; i <= n; i++ ) a[i] = true;
	for( int i = 2; i < Math.ceil(Math.sqrt(n)); i++ )if( a[i] ){
		temp.add(i);
		for( int j = 2*i; j <= n; j += i )a[j] = false;
	}
	return temp;
}