Summarize primes: Difference between revisions

m (Forth - faster without using a sieve)
Line 273:
Summarized primes 1-999: 21
</pre>
 
=={{header|C}}==
{{trans|C++}}
<lang c>#include <stdbool.h>
#include <stdio.h>
 
bool is_prime(int n) {
int i = 5;
 
if (n < 2) {
return false;
}
 
if (n % 2 == 0) {
return n == 2;
}
if (n % 3 == 0) {
return n == 3;
}
 
while (i * i <= n) {
if (n % i == 0) {
return false;
}
i += 2;
 
if (n % i == 0) {
return false;
}
i += 4;
}
 
return true;
}
 
int main() {
const int start = 1;
const int stop = 1000;
 
int sum = 0;
int count = 0;
int sc = 0;
int p;
 
for (p = start; p < stop; p++) {
if (is_prime(p)) {
count++;
sum += p;
if (is_prime(sum)) {
printf("The sum of %3d primes in [2, %3d] is %5d which is also prime\n", count, p, sum);
sc++;
}
}
}
printf("There are %d summerized primes in [%d, %d)\n", sc, start, stop);
 
return 0;
}</lang>
{{out}}
<pre>The sum of 1 primes in [2, 2] is 2 which is also prime
The sum of 2 primes in [2, 3] is 5 which is also prime
The sum of 4 primes in [2, 7] is 17 which is also prime
The sum of 6 primes in [2, 13] is 41 which is also prime
The sum of 12 primes in [2, 37] is 197 which is also prime
The sum of 14 primes in [2, 43] is 281 which is also prime
The sum of 60 primes in [2, 281] is 7699 which is also prime
The sum of 64 primes in [2, 311] is 8893 which is also prime
The sum of 96 primes in [2, 503] is 22039 which is also prime
The sum of 100 primes in [2, 541] is 24133 which is also prime
The sum of 102 primes in [2, 557] is 25237 which is also prime
The sum of 108 primes in [2, 593] is 28697 which is also prime
The sum of 114 primes in [2, 619] is 32353 which is also prime
The sum of 122 primes in [2, 673] is 37561 which is also prime
The sum of 124 primes in [2, 683] is 38921 which is also prime
The sum of 130 primes in [2, 733] is 43201 which is also prime
The sum of 132 primes in [2, 743] is 44683 which is also prime
The sum of 146 primes in [2, 839] is 55837 which is also prime
The sum of 152 primes in [2, 881] is 61027 which is also prime
The sum of 158 primes in [2, 929] is 66463 which is also prime
The sum of 162 primes in [2, 953] is 70241 which is also prime
There are 21 summerized primes in [1, 1000)</pre>
 
=={{header|C++}}==
1,452

edits