patterncMinor
C the sum of primes
Viewed 0 times
theprimessum
Problem
The challenge is to calculate the sum of the first 1000 primes. The code applies a sieve thanks to past answer, here, and works but I wonder about the flexibility of this solution.
#include
unsigned long compute_sum_of_primes(int primes_needed) {
int sieve_size = 20 * primes_needed;
int sieve[sieve_size];
unsigned long sum = 0;
for (int i = 0; i 0; prime++) {
if (sieve[prime]) {
sum += prime;
primes_needed--;
for (int composite = prime + prime; composite < sieve_size; composite += prime) {
sieve[composite] = 0;
}
}
}
return sum;
}
int main() {
unsigned long sum_of_primes = compute_sum_of_primes(1000);
printf("%lu\n", sum_of_primes);
}Solution
A simpler way to initialize the
However, although this works, know that it doesn't set the values to 1, but actually to 0x01010101 = 16843009, because
In your case this is fine, because you need effectively a boolean array, so as long as the values are nonzero, it doesn't make a difference that they are not actually 1 but 16843009.
However, readers might look suspiciously at the program. A comment explaining that the values are 16843009 may help, but a better way is to change the type of the array to
The number 20 here looks like pure magic:
At the minimum, it would be good to add a comment explaining this choice, and its implications in case of small and large values of n.
sieve variable-sized array is using memset (from #include ):memset(sieve, 1, sizeof(sieve));However, although this works, know that it doesn't set the values to 1, but actually to 0x01010101 = 16843009, because
memset sets bytes, regardless of the actual type of the underlying array.In your case this is fine, because you need effectively a boolean array, so as long as the values are nonzero, it doesn't make a difference that they are not actually 1 but 16843009.
However, readers might look suspiciously at the program. A comment explaining that the values are 16843009 may help, but a better way is to change the type of the array to
char. This way the array values will be really 1. But much more importantly, you will significantly reduce the memory footprint, to 25% of the original.The number 20 here looks like pure magic:
int sieve_size = 20 * primes_needed;At the minimum, it would be good to add a comment explaining this choice, and its implications in case of small and large values of n.
Code Snippets
memset(sieve, 1, sizeof(sieve));int sieve_size = 20 * primes_needed;Context
StackExchange Code Review Q#133405, answer score: 4
Revisions (0)
No revisions yet.