123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- #include <stdlib.h>
- #include <stdio.h>
- int empty(int element) {
- return element == -1 ? 1 : 0;
- }
- void primesieve(int *array, int limit) {
- /* generate array with numbers */
- for (int i = 0; i < limit; i++)
- array[i] = i + 1;
- /* filter non primes */
- for (int i = 0; i < limit; i++) {
- /* skip 0 / 1 */
- if (array[i] == 0 || array[i] == 1)
- continue;
- /* skip already replaced instances */
- if (empty(array[i]))
- continue;
- /* check rest of array for coprimeness */
- for (int p = i + 1; p < limit - i + 1; p++) {
- /* skip already replaces instances */
- if (empty(array[p]))
- continue;
- /* check coprimeness of values in current iteration */
- if (array[p] % array[i] == 0)
- array[p] = -1;
- }
- }
- }
- void printintarray(int *array, int arrayc) {
- printf("%i", array[0]);
- for (int i = 1; i < arrayc; i++) {
- if (empty(array[i]))
- continue;
- printf(" %i", array[i]);
- }
- printf("\n");
- }
- int main(int argc, char **argv) {
- if (argc < 2) {
- fprintf(stderr, "usage: ps limit\n");
- }
- int limit;
- sscanf(argv[1], "%i", &limit);
- int primes[limit];
- primesieve(primes, limit);
- printintarray(primes, limit);
- return 0;
- }
|