Sum of two adjacent numbers are primes: Difference between revisions

→‎{{header|C}}: Recoded to do extra credit.
(→‎{{header|Wren}}: Recoded to do extra credit.)
(→‎{{header|C}}: Recoded to do extra credit.)
Line 331:
 
=={{header|C}}==
{{trans|WrenGo}}
<lang c>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
 
#define TRUE 1
#define FALSE 0
 
typedef int bool;
int isPrime(int n) {
 
if (n < 2) return FALSE;
void primeSieve(int *c, int limit, bool processEven, bool primesOnly) {
if (!(n%2)) return n == 2;
ifint (!(n%3))i, returnix, np, == 3p2;
int d = 5limit++;
whilec[0] (d*d <= n) {TRUE;
returnc[1] = TRUE;
if (!(n%d)) return FALSE;
if (processEven) {
d += 2;
iffor (!(n%d)i = 4; i < limit; i +=2) returnc[i] = FALSETRUE;
d += 4;}
p = }3;
while (TRUE) {
p2 = p * p;
if (p2 >= limit) break;
for (i = p2; i < limit; i += 2*p) c[i] = TRUE;
while (TRUE) {
d p += 2;
if (!(n%dc[p])) return FALSEbreak;
n++;}
}
if (primesOnly) {
/* move the actual primes to the front of the array */
c[0] = 2;
for (i = 3, ix = 1; i < limit; i += 2) {
if (!c[i]) c[ix++] = i;
}
}
return TRUE;
}
 
int main() {
int counti, =p, 0hp, n = 110000000;
int limit = (int)(log(n) * (double)n * 1.2); /* should be more than enough */
int *primes = (int *)calloc(limit, sizeof(int));
primeSieve(primes, limit-1, FALSE, TRUE);
printf("The first 20 pairs of natural numbers whose sum is prime are:\n");
whilefor (counti = 1; i <= 20; ++i) {
ifp (isPrime(2*n= + 1)) {primes[i];
printf("%2d + %2dhp = %2d\n",p n, n + 1,/ 2*n + 1);
printf("%2d + %2d = count+%2d\n", hp, hp+1, p);
}
n++;
}
printf("\nThe 10 millionth such pair is:\n");
p = primes[n];
hp = p / 2;
printf("%2d + %2d = %2d\n", hp, hp+1, p);
free(primes);
return 0;
}</lang>
Line 387 ⟶ 410:
35 + 36 = 71
36 + 37 = 73
 
The 10 millionth such pair is:
89712345 + 89712346 = 179424691
</pre>
 
9,485

edits