Jump to content

Honaker primes: Difference between revisions

Added C
(Added Go)
(Added C)
Line 189:
[41 761 5801] [42 767 5843] [43 779 5927] [44 820 6301] [45 821 6311]
[46 826 6343] [47 827 6353] [48 847 6553] [49 848 6563] [50 857 6653]</pre>
 
=={{header|C}}==
{{trans|Wren}}
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <locale.h>
 
#define LIMIT 5000000
 
typedef struct {
int x;
int y;
} pair;
 
int *primeSieve(int limit, int *length) {
int i, p, *primes;
int j, pc = 0;
limit++;
// True denotes composite, false denotes prime.
bool *c = calloc(limit, sizeof(bool)); // all false by default
c[0] = true;
c[1] = true;
for (i = 4; i < limit; i += 2) c[i] = true;
p = 3; // Start from 3.
while (true) {
int p2 = p * p;
if (p2 >= limit) break;
for (i = p2; i < limit; i += 2 * p) c[i] = true;
while (true) {
p += 2;
if (!c[p]) break;
}
}
for (i = 0; i < limit; ++i) {
if (!c[i]) ++pc;
}
primes = (int *)malloc(pc * sizeof(int));
for (i = 0, j = 0; i < limit; ++i) {
if (!c[i]) primes[j++] = i;
}
free(c);
*length = pc;
return primes;
}
 
int digitSum(int n) {
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
 
int main() {
int i, count, length, hc = 0;
int *primes = (int *)primeSieve(LIMIT, &length);
pair h[50], h10000;
for (i = 1, count = 0; count < 10000; ++i) {
if (digitSum(i) == digitSum(primes[i-1])) {
++count;
if (count <= 50) {
h[hc++] = (pair){i, primes[i-1]};
} else if (count == 10000) {
h10000.x = i;
h10000.y = primes[i-1];
}
}
}
setlocale(LC_NUMERIC, "");
printf("The first 50 Honaker primes (index, prime):\n");
for (i = 0; i < 50; ++i) {
printf("(%3d, %'5d) ", h[i].x, h[i].y);
if (!((i+1)%5)) printf("\n");
}
printf("\nand the 10,000th: (%'7d, %'9d)\n", h10000.x, h10000.y);
free(primes);
return 0;
}</syntaxhighlight>
 
{{out}}
<pre>
The first 50 Honaker primes (index, prime):
( 32, 131) ( 56, 263) ( 88, 457) (175, 1,039) (176, 1,049)
(182, 1,091) (212, 1,301) (218, 1,361) (227, 1,433) (248, 1,571)
(293, 1,913) (295, 1,933) (323, 2,141) (331, 2,221) (338, 2,273)
(362, 2,441) (377, 2,591) (386, 2,663) (394, 2,707) (397, 2,719)
(398, 2,729) (409, 2,803) (439, 3,067) (446, 3,137) (457, 3,229)
(481, 3,433) (499, 3,559) (508, 3,631) (563, 4,091) (571, 4,153)
(595, 4,357) (599, 4,397) (635, 4,703) (637, 4,723) (655, 4,903)
(671, 5,009) (728, 5,507) (751, 5,701) (752, 5,711) (755, 5,741)
(761, 5,801) (767, 5,843) (779, 5,927) (820, 6,301) (821, 6,311)
(826, 6,343) (827, 6,353) (847, 6,553) (848, 6,563) (857, 6,653)
 
and the 10,000th: (286,069, 4,043,749)
</pre>
 
=={{header|C++}}==
9,482

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.