Concatenate two primes is also prime: Difference between revisions

Added C
(added Arturo)
(Added C)
Line 471:
end sub</syntaxhighlight>
 
 
=={{header|C}}==
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <locale.h>
 
bool isPrime(int n) {
if (n < 2) return false;
if (n%2 == 0) return n == 2;
if (n%3 == 0) return n == 3;
int d = 5;
while (d*d <= n) {
if (n%d == 0) return false;
d += 2;
if (n%d == 0) return false;
d += 4;
}
return true;
}
 
int compare(const void* a, const void* b) {
int arg1 = *(const int*)a;
int arg2 = *(const int*)b;
if (arg1 < arg2) return -1;
if (arg1 > arg2) return 1;
return 0;
}
 
int main() {
int primes[30] = {2}, results[200];
int i, j, p, q, pq, limit = 100, pc = 1, rc = 0;
for (i = 3; i < limit; i += 2) {
if (isPrime(i)) primes[pc++] = i;
}
for (i = 0; i < pc; ++i) {
p = primes[i];
for (j = 0; j < pc; ++j) {
q = primes[j];
pq = (q < 10) ? p * 10 + q : p * 100 + q;
if (isPrime(pq)) results[rc++] = pq;
}
}
qsort(results, rc, sizeof(int), compare);
setlocale(LC_NUMERIC, "");
printf("Two primes under 100 concatenated together to form another prime:\n");
for (i = 0, j = 0; i < rc; ++i) {
if (i > 0 && results[i] == results[i-1]) continue;
printf("%'6d ", results[i]);
if (++j % 10 == 0) printf("\n");
}
printf("\n\nFound %d such concatenated primes.\n", j);
return 0;
}</syntaxhighlight>
 
{{out}}
<pre>
Two primes under 100 concatenated together to form another prime:
23 37 53 73 113 137 173 193 197 211
223 229 233 241 271 283 293 311 313 317
331 337 347 353 359 367 373 379 383 389
397 433 523 541 547 571 593 613 617 673
677 719 733 743 761 773 797 977 1,117 1,123
1,129 1,153 1,171 1,319 1,361 1,367 1,373 1,723 1,741 1,747
1,753 1,759 1,783 1,789 1,913 1,931 1,973 1,979 1,997 2,311
2,341 2,347 2,371 2,383 2,389 2,917 2,953 2,971 3,119 3,137
3,167 3,719 3,761 3,767 3,779 3,797 4,111 4,129 4,153 4,159
4,337 4,373 4,397 4,723 4,729 4,759 4,783 4,789 5,323 5,347
5,923 5,953 6,113 6,131 6,143 6,173 6,197 6,719 6,737 6,761
6,779 7,129 7,159 7,331 7,919 7,937 8,311 8,317 8,329 8,353
8,389 8,923 8,929 8,941 8,971 9,719 9,743 9,767
 
Found 128 such concatenated primes.
</pre>
 
=={{header|Factor}}==
9,476

edits