Guest User

Untitled

a guest
Jul 20th, 2018
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. /* The number of primes to find */
  4. #define NPRIMES 50
  5.  
  6. /* List of primes */
  7. int primeList[NPRIMES];
  8.  
  9. /* Keeps track of the remainders modulo each smaller prime for the number being
  10. * checked for primality */
  11. int primeMod[NPRIMES];
  12.  
  13. int main() {
  14. /* The number of primes found so far */
  15. int nprimes = 0;
  16.  
  17. /* n is the number being checked for primality, i an index into
  18. * primeList/primeMod, and isPrime a flag */
  19. int n, i, isPrime;
  20.  
  21. for(n = 3; nprimes < NPRIMES; n += 2) {
  22. isPrime = 1;
  23.  
  24. for(i = 0; i < nprimes; i++) {
  25. /* Does n have a remainder of 0 modulo the prime at index i? This
  26. * is checked by seeing if the "modulus" equals the prime itself,
  27. * meaning it should really be 0 */
  28. if(primeList[i] == primeMod[i]) {
  29. /* If so, it is not prime */
  30. isPrime = 0;
  31. primeMod[i] = 1;
  32. }
  33. else {
  34. /* Strictly speaking, primeMod does not contain the remainders,
  35. * but the remainders divided by 2 (++ instead of += 2 below).
  36. * The reason we can get away with this is that 2m is divisible
  37. * by an odd number n exactly when m is divisible by n. */
  38. primeMod[i]++;
  39. }
  40.  
  41. /* Once the prime at index i is greater than n/2, there's no way it
  42. * can be a divisor of n, so we omit the check above and just update
  43. * the remaining remainders before we go on to the next prime
  44. * candidate. n/2 could also be implemented as a right shift here. */
  45. if(primeList[i] > n/2) {
  46. while(++i < nprimes)
  47. primeMod[i]++;
  48.  
  49. break;
  50. }
  51. }
  52.  
  53. if(isPrime) {
  54. printf("%d\n", n);
  55.  
  56. /* Register the new prime */
  57. primeList[nprimes] = n;
  58. primeMod[nprimes] = 1;
  59. nprimes++;
  60. }
  61. }
  62.  
  63. return 0;
  64. }
Add Comment
Please, Sign In to add comment