Skip to content

Commit f82e46f

Browse files
Merge pull request TheAlgorithms#5 from RianGallagher/master
Added Sieve of Eratosthenes algorithm for finding primes
2 parents 0634a30 + c97d806 commit f82e46f

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

FindingPrimes.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/*
2+
* The Sieve of Eratosthenes is an algorithm used to find prime numbers, up to a given value.
3+
* Illustration: https://upload.wikimedia.org/wikipedia/commons/b/b9/Sieve_of_Eratosthenes_animation.gif
4+
*/
5+
public class FindingPrimes{
6+
public static void main(String args[]){
7+
SOE(20); //Example: Finds all the primes up to 20
8+
}
9+
10+
public static void SOE(int n){
11+
boolean sieve[] = new boolean[n];
12+
13+
int check = (int)Math.round(Math.sqrt(n)); //No need to check for multiples past the square root of n
14+
15+
sieve[0] = false;
16+
sieve[1] = false;
17+
for(int i = 2; i < n; i++)
18+
sieve[i] = true; //Set every index to true except index 0 and 1
19+
20+
for(int i = 2; i< check; i++){
21+
if(sieve[i]==true) //If i is a prime
22+
for(int j = i+i; j < n; j+=i) //Step through the array in increments of i(the multiples of the prime)
23+
sieve[j] = false; //Set every multiple of i to false
24+
}
25+
for(int i = 0; i< n; i++){
26+
if(sieve[i]==true)
27+
System.out.print(i+" "); //In this example it will print 2 3 5 7 11 13 17 19
28+
}
29+
}
30+
}

0 commit comments

Comments
 (0)