Advertisement
OgreVorbis

Primes C

Nov 5th, 2021
1,180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.71 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 l, n, m, lim;
  10. char* nums;
  11. char input[255];
  12. clock_t start, stop;
  13.  
  14. int main()
  15. {
  16.     printf("Enter a limit for this search: ");
  17.     gets(input);
  18.     lim = atoi(input);
  19.  
  20.     start = clock();
  21.  
  22.     nums = (char *)malloc(lim);
  23.  
  24.     for (n = 2; n < sqrt(lim); n++)
  25.     {
  26.         if (nums[n] == FALSE)
  27.         {
  28.             m = n * n;
  29.             while (m <= lim)
  30.             {
  31.                 nums[m] = TRUE;
  32.                 m += n;
  33.             }
  34.         }
  35.     }
  36.  
  37.     stop = clock();
  38.  
  39.     printf("It took %f seconds.\n", (double)(stop - start) / 1000);
  40.     system("pause");
  41.  
  42.     for (n = 2; n < lim; n++)
  43.     {
  44.         if (nums[n] == FALSE)
  45.             printf("%d\n", n);
  46.     }
  47.  
  48.     free(nums);
  49.     return 0;
  50. }
  51.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement