Primes: Difference between revisions

From programming_contest
Jump to navigation Jump to search
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..."
 
(No difference)

Latest revision as of 04:02, 16 February 2015

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;
}