Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* The task: the sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
- * Find the sum of all the primes below two million. */
- /* Don't compile */
- /* A more efficient version */
- /* This version creates an array of non-prime numbers and then checks
- * all the values in the range of 2 to 2000000 against the array and
- * accumulates primes. */
- #include <stdio.h>
- int main()
- {
- int i, j;
- char non_primes[2000001] = { 0 };
- long int acc;
- for(i = 2; i <= 2000000; i++)
- for(j = 2; j <= 2000000 / i; j++)
- non_primes[i * j] = 1;
- for(i = 2; i <= 2000000; i++)
- if(non_primes[i] == 0)
- acc += i;
- printf("%ld", acc);
- return(0);
- }
- /* 142913828922
- * real 0m0,460s
- * user 0m0,442s
- * sys 0m0,004s */
- /* A less efficient version */
- /* The idea behind this solution is that if a number cannot be divided
- * by any smaller prime number it is prime itself. */
- #include <stdio.h>
- int main()
- {
- int primes[1999999] = {2};
- /* indices */
- int i, j;
- /* initialized to 2 because 2 is already in the array */
- long int sum = 2;
- /* current index of primes array */
- int mi = 0;
- /* prime flag */
- char pf;
- for(i = 3; i <= 2000000; i += 2)
- {
- pf = 1;
- for(j = 0; j <= mi; j++)
- {
- if(i % primes[j] == 0)
- {
- pf = 0;
- break;
- }
- }
- if(pf == 1)
- {
- mi++;
- primes[mi] = i;
- sum += i;
- }
- }
- printf("%ld\n", sum);
- return(0);
- }
- /* 142913828922
- *
- * real 1m27,239s
- * user 1m27,011s
- * sys 0m0,060s */
Add Comment
Please, Sign In to add comment