Prime reciprocal sum: Difference between revisions

Content added Content deleted
(Added C)
Line 28: Line 28:





=={{header|C}}==
{{libheader|GMP}}
{{trans|Wren}}
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <gmp.h>

void abbreviate(char a[], const char *s) {
size_t len = strlen(s);
if (len < 40) {
strcpy(a, s);
return;
}
strncpy(a, s, 20);
strcpy(a + 20, "...");
strncpy(a + 23, s + len - 20, 21);
}

int main() {
mpq_t q, r, s, u;
mpz_t p, t;
int count = 0, limit = 16;
size_t len;
bool isInteger;
char *ps, a[44];
mpq_inits(q, r, s, u, NULL);
mpq_set_ui(u, 1, 1);
mpz_inits(p, t, NULL);
printf("First %d elements of the sequence:\n", limit);
while (count < limit) {
mpq_sub(q, u, s);
mpq_inv(q, q);
mpq_get_den(t, q);
isInteger = !mpz_cmp_ui(t, 1);
mpz_set_q(p, q);
if (!isInteger) mpz_add_ui(p, p, 1);
mpz_nextprime(p, p);
++count;
ps = mpz_get_str(NULL, 10, p);
len = strlen(ps);
if (len <= 40) {
printf("%2d: %s\n", count, ps);
} else {
abbreviate(a, ps);
printf("%2d: %s (digits: %ld)\n", count, a, len);
}
mpq_set_z(r, p);
mpq_inv(r, r);
mpq_add(s, s, r);
}
mpq_clears(q, r, s, u, NULL);
mpz_clears(p, t, NULL);
return 0;
}</syntaxhighlight>

{{out}}
<pre>
First 16 elements of the sequence:
1: 2
2: 3
3: 7
4: 43
5: 1811
6: 654149
7: 27082315109
8: 153694141992520880899
9: 337110658273917297268061074384231117039
10: 84241975970641143191...13803869133407474043 (digits: 76)
11: 20300753813848234767...91313959045797597991 (digits: 150)
12: 20323705381471272842...21649394434192763213 (digits: 297)
13: 12748246592672078196...20708715953110886963 (digits: 592)
14: 46749025165138838243...65355869250350888941 (digits: 1180)
15: 11390125639471674628...31060548964273180103 (digits: 2358)
16: 36961763505630520555...02467094377885929191 (digits: 4711)
</pre>


=={{header|J}}==
=={{header|J}}==