Finding n-th number made of prime digits (2, 3, 5 and 7) only in C++


In this problem, we are given a number N. Our task is to finding n-th number made of prime digits (2, 3, 5 and 7) only.

The series consisting of prime digits only (2, 3, 5, 7) is, 2, 3, 5, 7, 22, 23, 25, 27, 32, 33...

Let's take an example to understand the problem,

Input: N = 6
Output: 23

Solution Approach

A simple approach to solving the problem is by finding the number at the given index i.e. by finding the term of the series, for this we will be observing the series.

We have four different prime numbers so the series made can be treated as a four-digit number system. In this number system, we have 4x numbers of length x.

Now to solve the problem, we have the series in which we will find the length o numbers that made them create the number. Then we will count the Nth number and print the required number.

To find the Nth number using the length we will be counting from the first number of length (x-1) and then count this N.

Example

Program to illustrate the working of our solution

#include <iostream>
#include <math.h>
using namespace std;
void findNthNumber(int n){
   long x = 1;
   long lastNum = 0;
   while (true) {
      long currNum = lastNum + pow(4, x);
      if (lastNum < n && currNum >= n)
         break;
      x++;
      lastNum = currNum;
   }
   for (int i = 1; i <= x; i++) {
      for (long j = 1; j <= 4; j++) {
         if (lastNum + pow(4, x - i) < n)
            lastNum += pow(4, x - i);
         else {
            if (j == 1)
               cout<<"2";
            else if (j == 2)
               cout<<"3";
            else if (j == 3)
               cout<<"5";
            else if (j == 4)
               cout<<"7";
            break;
         }
      }
   }
}
int main(){
   int N = 32;
   cout<<N<<"th number made of prime digits is ";
   findNthNumber(N);
   return 0;
}

Output

32th number made of prime digits is 257

Updated on: 01-Feb-2022

403 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements