I have a problem with my algorithm. I can't find where a go wrong in the task below.
Description:
The sum of the primes below
10is2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million.
Here is my solution in C:
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
int main() {
bool *numbers = (bool *)malloc(sizeof(bool) * 2000000);
unsigned long run = 1;
while (run < 2000000) {
numbers[run] = true;
run++;
}
unsigned long sum = 0;
for (long i = 2; i < 2000000; i++) {
if (numbers[i] == true) {
for (long x = 2 * i; x < 2000000; x += i) {
numbers[x] = false;
}
}
}
run = 0;
while (run < 2000000) {
if (numbers[run] == true) {
sum = sum + run;
}
run++;
}
printf("%d\n", sum-1); // cause 1
free(numbers);
return 0;
}
Thanks for help!!!
You can try something along these lines:
You can also invert the search to flag composite numbers rather than primes by using
callocvsmallocand save a loop (Thanks to Anti Haapala):Both print:
Note:
long longfor the sum which is guaranteed to be 64 bits. While a long may be 32 or 64 bits and anintmay be as short as 16 bits. See C data typesprintftype and length specifiers are correct given the data types being printed.