Created
August 26, 2013 20:42
-
-
Save bhavanki/6346430 to your computer and use it in GitHub Desktop.
Java implementation of Sieve of Eratosthenes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.List; | |
public class Sieve { | |
static List<Integer> sieve(int n) { | |
List<Integer> l = new java.util.ArrayList<Integer>(); | |
byte[] bs = new byte[(n / 8) + 1]; // 0 => maybe prime | |
bs[0] = (byte) 0xc0; // skip 0 and 1 | |
for (int i = 2; i <= n / 2; i++) { | |
for (int c = i; c <= n; c += i) { | |
int bidx = c / 8; | |
int bit = c % 8; // 2 -> 2, 7 -> 7, 8 -> 0, 9 -> 1 | |
byte mask = (byte) (1 << (7 - bit)); | |
if (c == i) { | |
if ((bs[bidx] & mask) != 0) { | |
break; | |
} | |
continue; | |
} | |
bs[bidx] |= mask; | |
} | |
} | |
int m = 0; | |
for (byte b : bs) { | |
for (int i = 7; i >= 0; i--) { | |
if ((b & (1 << i)) == 0) { | |
int prime = m + (7 - i); | |
if (prime > n) { | |
return l; | |
} | |
l.add(prime); | |
} | |
} | |
m += 8; | |
} | |
return l; | |
} | |
public static void main(String args[]) { | |
for (int i : sieve(Integer.parseInt(args[0]))) { | |
System.out.println(i); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment