Print prime numbers with prime sum of digits in an array

Given an array of elements, the task is to print those numbers that are prime and whose digit sum is also prime. This problem combines prime number checking with digit sum calculation.

Input: arr[]={2,4,3,19,25,6,11,12,18,7}
Output: 2, 3, 25, 11, 12, 7

The output contains numbers where both the number itself and its digit sum are prime. For example − 2, 3, 7 are prime numbers, while 25(2+5=7), 11(1+1=2), 12(1+2=3) have prime digit sums. Numbers like 19(1+9=10) are excluded because 10 is not prime.

Syntax

int isPrime(int num);
int digitSum(int num);
void printPrimeWithPrimeDigitSum(int arr[], int size);

Algorithm

START
Step 1 -> Take array of integers with values
Step 2 -> For each element in array:
   a) Check if number is prime
   b) If prime, calculate sum of its digits
   c) Check if digit sum is also prime
   d) If both conditions true, print the number
Step 3 -> Return -1 if no such numbers exist
STOP

Example

#include <stdio.h>

int isPrime(int num) {
    if (num <= 1) return 0;
    if (num <= 3) return 1;
    if (num % 2 == 0 || num % 3 == 0) return 0;
    
    for (int i = 5; i * i <= num; i += 6) {
        if (num % i == 0 || num % (i + 2) == 0)
            return 0;
    }
    return 1;
}

int digitSum(int num) {
    int sum = 0;
    while (num > 0) {
        sum += num % 10;
        num /= 10;
    }
    return sum;
}

int main() {
    int arr[] = {2, 4, 3, 19, 25, 6, 11, 12, 18, 7};
    int size = sizeof(arr) / sizeof(arr[0]);
    int found = 0;
    
    printf("Prime numbers with prime digit sum: ");
    
    for (int i = 0; i < size; i++) {
        if (isPrime(arr[i])) {
            int sum = digitSum(arr[i]);
            if (isPrime(sum)) {
                printf("%d ", arr[i]);
                found = 1;
            }
        }
    }
    
    if (!found) {
        printf("-1");
    }
    
    return 0;
}

Output

Prime numbers with prime digit sum: 2 3 11 25 12 7

How It Works

  • The isPrime() function checks if a number is prime using optimized trial division
  • The digitSum() function calculates the sum of digits by extracting each digit using modulo operation
  • For each array element, we first check if it's prime, then calculate its digit sum and check if that's also prime
  • Numbers satisfying both conditions are printed

Conclusion

This solution efficiently finds prime numbers with prime digit sums using separate functions for prime checking and digit sum calculation. The algorithm has a time complexity of O(n × ?m) where n is array size and m is the maximum number value.

Updated on: 2026-03-15T11:06:32+05:30

718 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements