Sum of two adjacent numbers are primes: Difference between revisions
Content added Content deleted
(→{{header|Wren}}: Recoded to do extra credit.) |
(→{{header|C}}: Recoded to do extra credit.) |
||
Line 331: | Line 331: | ||
=={{header|C}}== |
=={{header|C}}== |
||
{{trans| |
{{trans|Go}} |
||
<lang c>#include <stdio.h> |
<lang c>#include <stdio.h> |
||
#include <stdlib.h> |
|||
#include <math.h> |
|||
#define TRUE 1 |
#define TRUE 1 |
||
#define FALSE 0 |
#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; |
|||
int i, ix, p, p2; |
|||
limit++; |
|||
c[0] = TRUE; |
|||
⚫ | |||
⚫ | |||
if (processEven) { |
|||
⚫ | |||
for (i = 4; i < limit; i +=2) c[i] = TRUE; |
|||
} |
|||
⚫ | |||
while (TRUE) { |
|||
p2 = p * p; |
|||
if (p2 >= limit) break; |
|||
for (i = p2; i < limit; i += 2*p) c[i] = TRUE; |
|||
while (TRUE) { |
|||
⚫ | |||
⚫ | |||
⚫ | |||
} |
|||
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; |
|||
} |
|||
} |
} |
||
⚫ | |||
} |
} |
||
int main() { |
int main() { |
||
int |
int i, p, hp, n = 10000000; |
||
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"); |
printf("The first 20 pairs of natural numbers whose sum is prime are:\n"); |
||
for (i = 1; i <= 20; ++i) { |
|||
p = primes[i]; |
|||
hp = p / 2; |
|||
printf("%2d + %2d = %2d\n", hp, hp+1, p); |
|||
⚫ | |||
⚫ | |||
} |
} |
||
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; |
return 0; |
||
}</lang> |
}</lang> |
||
Line 387: | Line 410: | ||
35 + 36 = 71 |
35 + 36 = 71 |
||
36 + 37 = 73 |
36 + 37 = 73 |
||
The 10 millionth such pair is: |
|||
89712345 + 89712346 = 179424691 |
|||
</pre> |
</pre> |
||