Main.c 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. char* data = NULL;
  4. int hasBit(int index) {
  5. return (data[index >> 3] & (1 << (index & 7))) == 0;
  6. }
  7. void setBit(int index) {
  8. data[index >> 3] |= (1 << (index & 7));
  9. }
  10. int divideRound8(int i) {
  11. return (i >> 3) + ((i & 7) != 0);
  12. }
  13. int main(int argAmount, const char** args) {
  14. if(argAmount < 2) {
  15. if(argAmount > 0) {
  16. printf("%s <max_prime>\n", args[0]);
  17. } else {
  18. puts("... <max_prime>");
  19. }
  20. return 0;
  21. }
  22. int max = atoi(args[1]);
  23. if(max <= 0) {
  24. puts("max prime should be a positive number");
  25. return 0;
  26. }
  27. int end = (max - 1) >> 1;
  28. data = calloc(divideRound8(end), 1);
  29. int found = 0;
  30. if(max >= 2) {
  31. puts("2");
  32. found++;
  33. }
  34. for(int i = 0; i < end; i++) {
  35. if(hasBit(i)) {
  36. long prime = (i << 1) + 3;
  37. for(long k = i + prime; k < end; k += prime) {
  38. setBit(k);
  39. }
  40. printf("%ld\n", prime);
  41. found++;
  42. }
  43. }
  44. printf("found: %d\n", found);
  45. free(data);
  46. return 0;
  47. }