The Wayback Machine - https://web.archive.org/web/20220107053123/https://www.geeksforgeeks.org/count-prime-numbers-in-range-l-r-whose-single-digit-sum-is-also-prime/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Count prime numbers in range [L, R] whose single digit sum is also prime

  • Last Updated : 07 Jan, 2022

Given two integers L and R. The task is to count the prime numbers in the range [L, R], whose single sum is also a prime number. 
A single sum is obtained by adding the digits of a number until a single digit is left.

Examples

Input: L = 5, R = 20 
Output: 3
Explanation: Prime numbers in the range L = 5 to R = 20 are {5, 7, 11, 13, 17, 19}
Their “single sum” of digits is {5, 7, 2, 4, 8, 1}.  
Only {5, 7, 2} are prime. Hence the answer is 3.

Input: L = 1, R = 10  
Output: 4
Explanation: Prime numbers in the range L = 1 to R = 10 are {2, 3, 5, 7}.  
Their “single sum” of digits is {2, 3, 5, 7}.  
Since all the numbers are prime, hence the answer is 4.



 

Approach:  The naive approach is to iterate for each number in the range [L, R] and check if the number is prime or not. If the number is prime, find the single sum of its digits and again check whether the single sum is prime or not. If the single sum is prime, then increment the counter and print the current element in the range [L, R].

Below is the implementation of the above approach.

C++14




// C++ program for above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to check wheter number
// is prime or not
bool isPrime(int n)
{
    // Corner case
    if (n <= 1)
        return false;
  
    // Check from 2 to square root of n
    for (int i = 2; i <= sqrt(n); i++)
        if (n % i == 0)
            return false;
  
    return true;
}
  
// Function to find single digit sum
int SingleDigitSum(int& n)
{
    if (n <= 9)
        return n;
    return (n % 9 == 0) ? 9 : n % 9;
}
  
// Function to find single digit primes
int countSingleDigitPrimes(int l, int r)
{
    int count = 0, i;
  
    for (i = l; i <= r; i++) {
        if (isPrime(i)
            && isPrime(SingleDigitSum(i))) {
            count++;
        }
    }
    return count;
}
  
// Driver Code
int main()
{
    // Input range
    int L = 1, R = 10;
  
    // Function Call
    cout << countSingleDigitPrimes(L, R);
  
    return 0;
}
Output
2

Time Complexity: O((R – L)*N^(1/2)) where N is the prime number in the range [L, R].
Auxiliary Space: O(1)




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!