-
Notifications
You must be signed in to change notification settings - Fork 0
/
Eratosthenes.java
107 lines (103 loc) · 2.75 KB
/
Eratosthenes.java
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
103
104
105
106
107
public class Eratosthenes {
private float sqrtOfMax = -1;
public int[] createSequence( int maxNum)
{
sqrtOfMax = (float) Math.sqrt(maxNum);
int[] sequenceArray = new int[maxNum -1];
for( int index = 0; index < sequenceArray. length; index++)
{
sequenceArray[index] = index + 2;
}
return sequenceArray;
}
public int[] crossOutHigherMultiples(int[] sequenceArray, int primeNum )
{
if(sequenceArray != null ){
for( int index = 0; index < sequenceArray. length; index++)
{
if (sequenceArray[index] > primeNum)
{
if( ( sequenceArray[index] % primeNum) ==0)
{
sequenceArray[index] *= -1;
}
}
}
String sequenceString = sequenceToString(sequenceArray);
System.out.println( sequenceString);
}
return sequenceArray;
}
public int[] sieve( int userInput)
{
int[] mainSequence = createSequence(userInput);
String mainString = sequenceToString( mainSequence);
System.out.println( mainString);
int mainIndex = 0;
while(mainSequence[mainIndex] <= sqrtOfMax)
{
if( mainSequence[mainIndex] >=2 )
{
crossOutHigherMultiples( mainSequence, mainSequence[mainIndex]);
}
mainIndex++;
}
return mainSequence;
}
public String sequenceToString( int [] squenceArray )
{
String sequenceString = "";
if( squenceArray != null) {
for( int index = 0; index < squenceArray. length -1 ; index++)
{
if( squenceArray[index] >= 2)
{
String numString = Integer.toString(squenceArray[index]);
numString += ",";
sequenceString += numString;
}
else
{
String numString = "[";
numString += Integer.toString(Math.abs(squenceArray[index]));
numString += "],";
sequenceString += numString;
}
}
if( squenceArray[squenceArray. length -1] >= 2)
{
String numString = Integer.toString(squenceArray[squenceArray. length -1]);
sequenceString += numString;
}
else
{
String numString = "[";
numString += Integer.toString(Math.abs(squenceArray[squenceArray. length -1]));
numString += "]";
sequenceString += numString;
}
}
return sequenceString;
}
public String nonCrossedOutSubseqToString ( int [] squenceArray )
{
String sequenceString = "";
if( squenceArray != null) {
if( squenceArray[0] >= 2)
{
String numString = Integer.toString(squenceArray[0]);
sequenceString += numString;
}
for( int index = 1; index < squenceArray. length ; index++)
{
if( squenceArray[index] >= 2)
{
String numString = ",";
numString += Integer.toString(squenceArray[index]);
sequenceString += numString;
}
}
}
return sequenceString;
}
}