banovski

Project Euler, Problem #10, C

Feb 8th, 2022 (edited)
1,208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.77 KB | None | 0 0
  1. /* The task: the sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
  2.  * Find the sum of all the primes below two million. */
  3.  
  4. /* Don't compile */
  5.  
  6. /* A more efficient version */
  7.  
  8. /* This version creates an array of non-prime numbers and then checks
  9.  * all the values in the range of 2 to 2000000 against the array and
  10.  * accumulates primes. */
  11.  
  12. #include <stdio.h>
  13.  
  14. int main()
  15. {
  16.      int i, j;
  17.      char non_primes[2000001] = { 0 };
  18.      long int acc;
  19.      for(i = 2; i <= 2000000; i++)
  20.           for(j = 2; j <= 2000000 / i; j++)
  21.                non_primes[i * j] = 1;
  22.  
  23.      for(i = 2; i <= 2000000; i++)
  24.           if(non_primes[i] == 0)
  25.                acc += i;
  26.      
  27.      printf("%ld", acc);
  28.      return(0);
  29. }
  30.  
  31. /* 142913828922
  32.  * real 0m0,460s
  33.  * user 0m0,442s
  34.  * sys  0m0,004s */
  35.  
  36.  
  37. /* A less efficient version */
  38.  
  39. /* The idea behind this solution is that if a number cannot be divided
  40.  * by any smaller prime number it is prime itself. */
  41.  
  42. #include <stdio.h>
  43.  
  44. int main()
  45. {
  46.      int primes[1999999] = {2};
  47.      /* indices */
  48.      int i, j;
  49.      /* initialized to 2 because 2 is already in the array */
  50.      long int sum = 2;
  51.      /* current index of primes array */
  52.      int mi = 0;
  53.      /* prime flag */
  54.      char pf;
  55.  
  56.      for(i = 3; i <= 2000000; i += 2)
  57.      {
  58.           pf = 1;
  59.           for(j = 0; j <= mi; j++)
  60.           {
  61.                if(i % primes[j] == 0)
  62.                {
  63.                     pf = 0;
  64.                     break;
  65.                }
  66.           }
  67.                
  68.           if(pf == 1)
  69.           {
  70.                mi++;
  71.                primes[mi] = i;
  72.                sum += i;
  73.           }
  74.      }
  75.      printf("%ld\n", sum);
  76.      return(0);
  77. }
  78.  
  79. /* 142913828922
  80.  *
  81.  * real 1m27,239s
  82.  * user 1m27,011s
  83.  * sys  0m0,060s */
  84.  
Add Comment
Please, Sign In to add comment