ps.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. int empty(int element) {
  4. return element == -1 ? 1 : 0;
  5. }
  6. void primesieve(int *array, int limit) {
  7. /* generate array with numbers */
  8. for (int i = 0; i < limit; i++)
  9. array[i] = i + 1;
  10. /* filter non primes */
  11. for (int i = 0; i < limit; i++) {
  12. /* skip 0 / 1 */
  13. if (array[i] == 0 || array[i] == 1)
  14. continue;
  15. /* skip already replaced instances */
  16. if (empty(array[i]))
  17. continue;
  18. /* check rest of array for coprimeness */
  19. for (int p = i + 1; p < limit - i + 1; p++) {
  20. /* skip already replaces instances */
  21. if (empty(array[p]))
  22. continue;
  23. /* check coprimeness of values in current iteration */
  24. if (array[p] % array[i] == 0)
  25. array[p] = -1;
  26. }
  27. }
  28. }
  29. void printintarray(int *array, int arrayc) {
  30. printf("%i", array[0]);
  31. for (int i = 1; i < arrayc; i++) {
  32. if (empty(array[i]))
  33. continue;
  34. printf(" %i", array[i]);
  35. }
  36. printf("\n");
  37. }
  38. int main(int argc, char **argv) {
  39. if (argc < 2) {
  40. fprintf(stderr, "usage: ps limit\n");
  41. }
  42. int limit;
  43. sscanf(argv[1], "%i", &limit);
  44. int primes[limit];
  45. primesieve(primes, limit);
  46. printintarray(primes, limit);
  47. return 0;
  48. }