-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSieveOfEratosthenes.java
More file actions
102 lines (88 loc) · 2.62 KB
/
SieveOfEratosthenes.java
File metadata and controls
102 lines (88 loc) · 2.62 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import java.util.Arrays;
import java.util.Scanner;
public class SieveOfEratosthenes {
public static final int STARTING_INDEX = 2;
public static void main(String[] args) {
boolean quit = false;
while(!quit)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a number greater than 2 or enter quit to end.");
if(input.hasNextInt()){
int limit = input.nextInt();
if(limit < 2)
System.out.println("The number you have entered is too low");
else{
boolean[] array = createSequence(limit);
System.out.println(sequenceToString(array));
int index = STARTING_INDEX;
while(index * index < limit){
while(array[index-STARTING_INDEX] == false && index < limit)
index++;
crossOutHigherMultiples(array,index);
System.out.println(sequenceToString(array));
index++;
}
System.out.println(nonCrossedOutSubseqToString(array));
}
}
else if(input.hasNext("quit"))
{
quit = true;
}
else{
System.out.println("Not a valid input!");
}
}
}
public static boolean[] createSequence(int arraySize){
boolean[] sequenceArray = new boolean[arraySize];
for(int index = 0;index < arraySize;index++){
sequenceArray[index] = true;
}
return sequenceArray;
}
public static boolean[] crossOutHigherMultiples(boolean[] array,int number){
if (array != null) {
for (int index = number + number; index <= array.length; index += number) {
if (index % number == 0)
array[index - STARTING_INDEX] = false;
}
return array;
} else
return array;
}
public static boolean[] sieve(boolean[] array){
for (int index = STARTING_INDEX; index <= array.length; index++)
array = crossOutHigherMultiples(array, index);
return array;
}
public static String sequenceToString(boolean[] array){
String sequence = "";
if (array != null) {
for (int index = 0; index < array.length - 1; index++) {
if (array[index])
sequence = sequence + (index + STARTING_INDEX);
else
sequence = sequence + "[" + (index + STARTING_INDEX) + "]";
if (index + STARTING_INDEX != array.length)
sequence = sequence + ",";
}
return sequence;
} else
return sequence;
}
public static String nonCrossedOutSubseqToString(boolean[] array){
String sequence = "";
if (array != null) {
for (int index = 0; index < array.length - 1; index++) {
if (index > 0 && array[index])
sequence = sequence + "," + (index + STARTING_INDEX);
else if (array[index])
sequence = sequence + (index + STARTING_INDEX);
}
return sequence;
} else
return sequence;
}
}