Prime Minister's number

Our Prime Minister has some secret numbers, so as in any case of emergency he can use them to contact the Avengers to save him. But these numbers have some special features, they are prime and sum of each individual's digit is also prime. Like 23, it is a prime number and the sum of its digits (2+3)= 5, is also a prime number.

For your information, Avengers are Earth's Mightiest Heroes , consisting of Iron Man, Captain America, Thor, Hulk and many more.

So your task is to print all the such numbers  in a given range, a,b (both included), in ascending order.

Save your PM.

Example:

Input:  a = 10,  b = 50
Output: 11 23 29 41 43 47

Approach

C++

#include <bits/stdc++.h>
using namespace std;

int sumOfDigits(int n)
{
    int res = 0;
    while (n)
    {
        res += n % 10;
        n = n / 10;
    }
    return res;
}
bool prime[1000001];
void primeInitialize()
{

    memset(primetruesizeof(prime));
    prime[0] = false;
    prime[1] = false;
    for (int i = 2i * i <= 1000001i++)
    {
        if (prime[i])
        {
            for (int j = i * ij <= 1000001j += i)
                prime[j] = false;
        }
    }
}

void primeMinNumbers(int aint b)
{
    int cnt = 0;
    for (int i = ai <= bi++)
    {
        int sum = sumOfDigits(i);

        if (prime[i] && prime[sum])
            cout << i << " ";
    }
}
int main()
{
    int a = 10b = 50;

    primeInitialize();

    primeMinNumbers(ab);

    return 0;
}


No comments:

Post a Comment