University stuff.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Sieve.java 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /*
  2. * I use 0 to represent prime and 1 to represent not prime,
  3. * because a byte[] is initialized to all 0.
  4. *
  5. * Stores prime/not prime in all 8 bits in each byte.
  6. */
  7. class Sieve {
  8. public byte[] arr;
  9. public int maxNum;
  10. public boolean smallPrimesGenerated = false;
  11. private int sqrtNum;
  12. Sieve(int maxNum, byte[] arr) {
  13. this.maxNum = maxNum;
  14. this.sqrtNum = (int)Math.ceil(Math.sqrt(maxNum));
  15. this.arr = arr;
  16. }
  17. Sieve(int maxNum) {
  18. this(maxNum, new byte[(maxNum / 16) + 1]);
  19. }
  20. // Find all prime numbers.
  21. public void generatePrimes(int step, int offset) {
  22. if (!smallPrimesGenerated)
  23. generateSmallPrimes();
  24. for (int i = 2 + offset; i <= sqrtNum; i += (step * 2)) {
  25. if (isPrime(i)) {
  26. setNotPrimes(i, maxNum);
  27. }
  28. }
  29. }
  30. public void generatePrimes() {
  31. generatePrimes(1, 1);
  32. }
  33. // Set all multiples of i as not primes
  34. private void setBigPrimes(int i) {
  35. int j = 1;
  36. }
  37. // Find the first sqrt(n) prime numbers, and set them
  38. // as not prime.
  39. public void generateSmallPrimes() {
  40. smallPrimesGenerated = true;
  41. for (int i = 3; i <= sqrtNum; i += 2) {
  42. if (isPrime(i))
  43. setNotPrimes(i, sqrtNum);
  44. }
  45. }
  46. // Check whether a number is prime (aka if its bit is 0)
  47. public boolean isPrime(int i) {
  48. if (i == 2)
  49. return true;
  50. if ((i & 1) == 0)
  51. return false;
  52. byte b = arr[byteIndex(i)];
  53. return (b & (1 << bitIndex(i))) == 0;
  54. }
  55. // Set all multiples of i under sqrt(n) as not primes
  56. private void setNotPrimes(int min, int max) {
  57. int j = min;
  58. min *= 2;
  59. int mul = 3;
  60. while (min <= max) {
  61. setNotPrime(min);
  62. min = j * mul;
  63. mul += 2;
  64. }
  65. }
  66. // Get the byte a number's bit is in
  67. private int byteIndex(int i) {
  68. return i >> 4;
  69. }
  70. // Get what bit in the byte a number is in
  71. private int bitIndex(int i) {
  72. return (i % 16) >> 1;
  73. }
  74. // Set a number to be not prime (aka set its bit to 1)
  75. private void setNotPrime(int i) {
  76. // No need to store even numbers
  77. if (i % 2 == 0)
  78. return;
  79. int bi = byteIndex(i);
  80. arr[bi] = (byte)(arr[bi] | (1 << bitIndex(i)));
  81. }
  82. }