-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathPrintPrimes.java
86 lines (76 loc) · 2.42 KB
/
PrintPrimes.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
public class PrintPrimes {
int numberOfPrimes;
int RR;
int CC;
int WW;
int ORDMAX;
int listOfPrimes[];
public PrintPrimes(int numberOfPrimes, int RR, int CC, int WW, int ORDMAX) {
this.numberOfPrimes = numberOfPrimes;
this.RR = RR;
this.CC = CC;
this.WW = WW;
this.ORDMAX = ORDMAX;
this.listOfPrimes = new int[numberOfPrimes + 1];
}
public static void main(String[] args) {
PrintPrimes printPrimes = new PrintPrimes(300, 50, 4, 10, 30);
printPrimes.calculatePrimes();
printPrimes.printPrimes();
}
public void calculatePrimes() {
/* Two is the only even prime. All other prime numbers are odd.
* To simplify the code, we simply add 2 as a prime number, and
* delegate the task of finding all odd prime numbers to a helper
* function.
*/
listOfPrimes[1] = 2;
calculateOddPrimes();
}
private void calculateOddPrimes() {
boolean JPRIME;
int N;
int MULT[] = new int[ORDMAX + 1];
int J = 1;
int ORD = 2;
int SQUARE = 9;
for(int primesFoundSoFar = 1; primesFoundSoFar <= numberOfPrimes; primesFoundSoFar++) {
do {
J = J + 2;
if (J == SQUARE) {
ORD = ORD + 1;
SQUARE = listOfPrimes[ORD] * listOfPrimes[ORD];
MULT[ORD - 1] = J;
}
N = 2;
JPRIME = true;
while (N < ORD && JPRIME) {
while (MULT[N] < J)
MULT[N] = MULT[N] + listOfPrimes[N] + listOfPrimes[N];
if (MULT[N] == J)
JPRIME = false;
N = N + 1;
}
} while (!JPRIME);
listOfPrimes[primesFoundSoFar] = J;
}
}
public void printPrimes() {
int PAGENUMBER = 1;
int PAGEOFFSET = 1;
while (PAGEOFFSET <= numberOfPrimes) {
System.out.println("The First " + numberOfPrimes +
" Prime Numbers --- Page " + PAGENUMBER);
System.out.println("");
for (int ROWOFFSET = PAGEOFFSET; ROWOFFSET < PAGEOFFSET + RR; ROWOFFSET++){
for (int C = 0; C < CC;C++)
if (ROWOFFSET + C * RR <= numberOfPrimes)
System.out.format("%10d", listOfPrimes[ROWOFFSET + C * RR]);
System.out.println("");
}
System.out.println("\f");
PAGENUMBER = PAGENUMBER + 1;
PAGEOFFSET = PAGEOFFSET + RR * CC;
}
}
}