Skip to content

Commit 03430ea

Browse files
committed
Updated 1 solution
1 parent 8521019 commit 03430ea

File tree

1 file changed

+8
-14
lines changed
  • Chp. 06 - Math and Logic Puzzles/__Intro_Prime

1 file changed

+8
-14
lines changed

Chp. 06 - Math and Logic Puzzles/__Intro_Prime/Prime.java

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -24,28 +24,22 @@ public static boolean isPrime(int n) {
2424
/* Solution 2: Sieve of Eratosthenes */
2525
public static boolean[] generatePrimes(int max) {
2626
boolean[] flags = new boolean[max + 1];
27-
initialize(flags);
27+
for (int i = 2; i < flags.length; i++) {
28+
flags[i] = true;
29+
}
30+
2831
int prime = 2;
2932
int sqrt = (int) Math.sqrt(max);
3033
while (prime <= sqrt) { // see comment in crossOff() to see why we stop at sqrt(max)
31-
crossOff(flags, prime);
34+
crossOffMultiplesOfPrime(flags, prime);
3235
prime = getNextPrime(flags, prime);
3336
}
3437
return flags;
3538
}
3639

37-
private static void initialize(boolean[] flags) {
38-
flags[0] = false;
39-
flags[1] = false;
40-
for (int i = 2; i < flags.length; i++) {
41-
flags[i] = true;
42-
}
43-
}
44-
45-
/* Cross off multiples of prime from our array */
46-
private static void crossOff(boolean[] flags, int prime) {
47-
/* We can start with (prime*prime), because if we have k * prime, where k < prime,
48-
this value would have already been crossed off in a prior call to this function */
40+
private static void crossOffMultiplesOfPrime(boolean[] flags, int prime) {
41+
// We can start with (prime*prime), because if we have k * prime, where k < prime,
42+
// this value would have already been crossed off in a prior call to this function
4943
for (int i = prime * prime; i < flags.length; i += prime) {
5044
flags[i] = false;
5145
}

0 commit comments

Comments
 (0)