File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments