Advertisement
Guest User

primes.c

a guest
Jun 10th, 2016
521
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.10 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. int main(int argc, char *argv[])
  4. {
  5.   int x=1000000; //default 1 million primes
  6.   if (argc > 1) x = (int)(strtol(argv[1], NULL, 10));
  7.   printf ("Program will calculate %i prime",x); if(x!=1) printf("s"); printf(". Size of int is %lu bytes. Tap enter to start allocating memory.\n",sizeof(int));
  8.   getchar();
  9.   int howmanyprimes=x-1;
  10.   unsigned int* primes=calloc(howmanyprimes, sizeof(int));
  11.   int iscomposite = 0;
  12.   primes[0] = 3;
  13.   unsigned int index = 0;
  14.   if (x==0)
  15.   {
  16.     return 0;
  17.   }
  18.   if (x==1)
  19.   {
  20.     printf ("2 \nTap enter key to exit.");
  21.     getchar();
  22.     return 0;
  23.   }
  24.   printf ("2 ");
  25.   unsigned int n = 0;
  26.   for (n=3;;n+=2)
  27.   {
  28.     iscomposite=0;
  29.     unsigned int n2 = 0;
  30.     for (n2=0;primes[n2]*primes[n2]<=n;n2++)
  31.     {
  32.       if ((n%primes[n2])==0)
  33.       {
  34.         iscomposite = 1;
  35.         break;
  36.       }
  37.     }
  38.     if (iscomposite==0)
  39.     {
  40.       index++;
  41.       primes[index]=n;
  42.       printf ("%i ",n);
  43.     }
  44.     if (index>howmanyprimes-1) break;
  45.   }
  46.   printf("\nTap enter key to exit.");
  47.   getchar();
  48.   return 0;
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement