Advertisement
OgreVorbis

Primes C (Working)

Nov 11th, 2021
2,142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.30 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <math.h>
  4. #include <time.h>
  5.  
  6. #define TRUE 1
  7. #define FALSE 0
  8.  
  9. int main(int argc, char* argv[])
  10. {
  11.     int n, m, lim;
  12.     double s;
  13.     char* nums;
  14.     char input[255];
  15.     clock_t start, stop;
  16.  
  17.     if (argc == 2)
  18.         lim = atoi(argv[1]);
  19.     else
  20.     {
  21.         printf("Enter a limit for this search (empty for default): ");
  22.         gets(input);
  23.         if (input[0])
  24.             lim = atoi(input);
  25.         else
  26.             lim = 100000000;
  27.     }
  28.  
  29.     s = sqrt(lim);
  30.  
  31.     start = clock();
  32.  
  33.     nums = (char *)calloc(lim + 1, sizeof(char));
  34.  
  35.     for (n = 2; n < s; n++)
  36.     {
  37.         if (nums[n] == FALSE)
  38.         {
  39.             m = n * n;
  40.             while (m <= lim)
  41.             {
  42.                 nums[m] = TRUE;
  43.                 m += n;
  44.             }
  45.         }
  46.     }
  47.  
  48.     stop = clock();
  49.  
  50.     printf("It took %f seconds.\n", (double)(stop - start) / 1000);
  51.     printf("Do you want to list the results, count total, or do nothing (L/C/N)? ");
  52.     gets(input);
  53.     if (input[0] == 'L' || input[0] == 'l' || input[0] == 'C' || input[0] == 'c')
  54.     {
  55.         m = 0;
  56.         for (n = 2; n < lim; n++)
  57.         {
  58.             if (nums[n] == FALSE)
  59.             {
  60.                 if (input[0] == 'L' || input[0] == 'l')
  61.                     printf("%d\n", n);
  62.                 m++;
  63.             }
  64.         }
  65.         printf("Total primes = %d\n\n", m);
  66.         printf("Press ENTER to exit. . . ");
  67.         getchar();
  68.     }
  69.  
  70.     free(nums);
  71.     return 0;
  72. }
  73.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement