Advertisement
Guest User

Untitled

a guest
Dec 12th, 2019
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.65 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5.  
  6. #define PRIMELISTSIZE 100000
  7.  
  8. int uppercheck = 0;
  9.  
  10. int is_prime(int c, int m, int *primes) {
  11.     int i, p;
  12.  
  13.     for (i = 0; i <= m; i++)
  14.     {
  15.         p = primes[i];
  16.         if (c % p == 0)
  17.         {
  18.             return(1);
  19.         }
  20.     }
  21.     return(0);
  22. }
  23.  
  24. int main(int argc, char **argv) {
  25.     int i, square;
  26.     int curListLength = 1;
  27.     int primelistsize = PRIMELISTSIZE;
  28.  
  29.     int opt;
  30.  
  31.     // put ':' in the starting of the
  32.     // string so that program can
  33.     //distinguish between '?' and ':'
  34.  
  35.     while((opt = getopt(argc, argv, "m:")) != -1)
  36.     {
  37.         switch(opt)
  38.         {
  39.             case 'm':
  40.                 primelistsize = atoi(optarg);
  41.                 break;
  42.             case ':':
  43.                 printf("option needs a value\n");
  44.                 break;
  45.         }
  46.     }
  47.  
  48.     // optind is for the extra arguments
  49.     // which are not parsed
  50.     for(; optind < argc; optind++){
  51.         printf("extra arguments: %s\n", argv[optind]);
  52.     }
  53.  
  54.     int primes[primelistsize];
  55.     primes[0] = 2;
  56.     int candidate = 3;
  57.  
  58.     square = primes[uppercheck] * primes[uppercheck];
  59.     while (curListLength < primelistsize)
  60.     {
  61.  
  62.         if (square <  candidate) {
  63.             uppercheck++;
  64.             square = primes[uppercheck] * primes[uppercheck];
  65.         }
  66.  
  67.         if (is_prime(candidate, uppercheck, primes) == 0)
  68.             {
  69.                 primes[curListLength] = candidate; curListLength++;
  70.             }
  71.         candidate += 2;
  72.     }
  73.  
  74.     for (i = 0; i < primelistsize; i++)
  75.         printf("%d\n", primes[i]);
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement