How to find two prime numbers that, when concatenated, form another prime number in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h> // atoll
#include <stdbool.h>

// Function to check primality
bool isPrime(long long n) {
    if (n < 2) return false;
    if (n % 2 == 0 && n != 2) return false;

    for (long long i = 3; i * i <= n; i += 2) {
        if (n % i == 0) return false;
    }

    return true;
}

// Concatenate two integers
long long concat(int a, int b) {
    char buffer[64];
    snprintf(buffer, sizeof(buffer), "%d%d", a, b);
    
    return atoll(buffer);
}

int main(void) {
    int limit = 12; // you can increase this
    int primes[64]; // fixed-size array for simplicity
    int primeCount = 0;

    // Generate primes up to limit
    for (int i = 2; i <= limit; i++) {
        if (isPrime(i)) {
            primes[primeCount++] = i;
        }
    }

    // Check pairs
    for (int i = 0; i < primeCount; i++) {
        for (int j = 0; j < primeCount; j++) {
            if (i == j) continue; // skip same prime if you want
            long long num = concat(primes[i], primes[j]);
            if (isPrime(num)) {
                printf("%d + %d -> %lld is prime\n",
                       primes[i], primes[j], num);
            }
        }
    }

    return 0;
}



/*
run:

2 + 3 -> 23 is prime
2 + 11 -> 211 is prime
3 + 7 -> 37 is prime
3 + 11 -> 311 is prime
5 + 3 -> 53 is prime
7 + 3 -> 73 is prime
11 + 3 -> 113 is prime

*/

 



answered Nov 28, 2025 by avibootz
edited Nov 28, 2025 by avibootz
...