forked from williamfiset/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompressedPrimeSieve.java
More file actions
70 lines (63 loc) · 2.12 KB
/
CompressedPrimeSieve.java
File metadata and controls
70 lines (63 loc) · 2.12 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
/**
* Generates a compressed prime sieve using bit manipulation. Each bit represents whether an odd
* number is prime or not. Even numbers are omitted (except 2, handled as a special case), so each
* long covers a range of 128 numbers.
*
* <p>Time: ~O(n log(log(n)))
*
* <p>Space: O(n / 128) longs
*
* @author William Fiset, william.alexandre.fiset@gmail.com
*/
package com.williamfiset.algorithms.math;
public class CompressedPrimeSieve {
private static final double NUM_BITS = 128.0;
private static final int NUM_BITS_SHIFT = 7; // 2^7 = 128
// Marks n as not prime by setting its bit to 1.
private static void setBit(long[] arr, int n) {
if ((n & 1) == 0)
return;
arr[n >> NUM_BITS_SHIFT] |= 1L << ((n - 1) >> 1);
}
// Returns true if n's bit is unset (meaning n is prime).
private static boolean isNotSet(long[] arr, int n) {
if (n < 2)
return false;
if (n == 2)
return true;
if ((n & 1) == 0)
return false;
long chunk = arr[n >> NUM_BITS_SHIFT];
long mask = 1L << ((n - 1) >> 1);
return (chunk & mask) != mask;
}
/** Returns true if n is prime according to the given sieve. */
public static boolean isPrime(long[] sieve, int n) {
return isNotSet(sieve, n);
}
/**
* Builds a compressed prime sieve for all numbers up to {@code limit}.
*
* @param limit the upper bound (inclusive) for the sieve.
* @return a bit-packed array where each bit indicates whether an odd number is composite.
*/
public static long[] primeSieve(int limit) {
int numChunks = (int) Math.ceil(limit / NUM_BITS);
int sqrtLimit = (int) Math.sqrt(limit);
long[] chunks = new long[numChunks];
chunks[0] = 1; // Mark 1 as not prime.
for (int i = 3; i <= sqrtLimit; i += 2)
if (isNotSet(chunks, i))
for (int j = i * i; j <= limit; j += i)
if (isNotSet(chunks, j))
setBit(chunks, j);
return chunks;
}
public static void main(String[] args) {
int limit = 200;
long[] sieve = primeSieve(limit);
for (int i = 0; i <= limit; i++)
if (isPrime(sieve, i))
System.out.printf("%d is prime!\n", i);
}
}