forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindingPrimes.java
More file actions
41 lines (36 loc) · 1.15 KB
/
Copy pathFindingPrimes.java
File metadata and controls
41 lines (36 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import java.util.Scanner;
public class FindingPrimes{
/**
* The Main method
*
* @param args Command line arguments
*/
public static void main(String args[]){
Scanner entry = new Scanner(System.in);
System.out.println("Up to wich number do you want to see the primes?:");
int n = entry.nextInt();
SOE(n); //Example: Finds all the primes up to 20
}
/**
* The method implementing the Sieve of Eratosthenes
*
* @param n Number to perform SOE on
*/
public static void SOE(int n){
boolean sieve[] = new boolean[n];
int check = (int)Math.round(Math.sqrt(n)); //No need to check for multiples past the square root of n
sieve[0] = false;
sieve[1] = false;
for(int i = 2; i < n; i++)
sieve[i] = true; //Set every index to true except index 0 and 1
for(int i = 2; i< check; i++){
if(sieve[i]==true) //If i is a prime
for(int j = i+i; j < n; j+=i) //Step through the array in increments of i(the multiples of the prime)
sieve[j] = false; //Set every multiple of i to false
}
for(int i = 0; i< n; i++){
if(sieve[i]==true)
System.out.print(i+" "); //In this example it will print 2 3 5 7 11 13 17 19
}
}
}