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

11 Mar, 2022
Given a number ‘n’, we need to find the nth number whose each digit is a prime number i.e 2, 3, 5, 7....In other words you have to find nth number of this sequence. 2, 3, 5, 5, 22, 23...... Given that the nth number such found will be less then equal to 10^18 Examples :  
Input  : 10
Output : 33
         2, 3, 5, 7, 22, 23, 25, 
         27, 32, 33

Input  : 21
Output : 222
 
There are four prime digits 2, 3, 5 and 7. First observation is that the number of numbers of x length and made of prime digits are because for each position you have 4 choices so total number is 4^x. So total count of such numbers whose length is = 1 to len (i.e. 2 or 3 or more) will be 4*((4len – 1)/3). (This is sum of G.P with first term 4 and common ratio 4)The algorithm is mainly divided in two steps.  
We find the number of digits in n-th number using above observation. We start from len = 0 and keep incrementing it while value of it is smaller than 4*((4len – 1)/3).Now we know number of digits in n-th number. We also know the count of numbers with with (len-1) digits. Let this count be ‘prev_count’. Now we one by one find digits in our result. First fix 2 at i-th place (assuming all the places upto i-1 are already filled), we have 4^(len – i) numbers possible and to check if 2 is the right candidate or not check if count of numbers after putting 2 is greater than or equal to n or not. If it is true then 2 is the right candidate if this is not true this means if we fix 2 at ith place only prev_count + 4^(len-i) numbers can be covered. So increase prev_count by 4^(len-i) and repeat this step for 3 check if 3 fits at ith place or not .If not go for 5. If 5 also does not fit, go for 7. It is guaranteed that 7 will fit it if 2, 3 and 5 do not fit, because we are sure that the length of nth such number is len only.
We find the number of digits in n-th number using above observation. We start from len = 0 and keep incrementing it while value of it is smaller than 4*((4len – 1)/3).
Now we know number of digits in n-th number. We also know the count of numbers with with (len-1) digits. Let this count be ‘prev_count’. Now we one by one find digits in our result. First fix 2 at i-th place (assuming all the places upto i-1 are already filled), we have 4^(len – i) numbers possible and to check if 2 is the right candidate or not check if count of numbers after putting 2 is greater than or equal to n or not. If it is true then 2 is the right candidate if this is not true this means if we fix 2 at ith place only prev_count + 4^(len-i) numbers can be covered. So increase prev_count by 4^(len-i) and repeat this step for 3 check if 3 fits at ith place or not .If not go for 5. If 5 also does not fit, go for 7. It is guaranteed that 7 will fit it if 2, 3 and 5 do not fit, because we are sure that the length of nth such number is len only.
Below is implementation of above steps.  
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation for finding nth number// made of prime digits only#include <bits/stdc++.h>using namespace std; // Prints n-th number where each digit is a// prime numbervoid nthprimedigitsnumber(long long n){    // Finding the length of n-th number    long long len = 1;     // Count of numbers with len-1 digits    long long prev_count = 0;    while (true) {        // Count of numbers with i digits        long long curr_count = prev_count + pow(4, len);         // if i is the length of such number        // then n<4*(4^(i-1)-1)/3 and n>= 4*(4 ^ i-1)/3        // if a valid i is found break the loop        if (prev_count < n && curr_count >= n)            break;         // check for i + 1        len++;         prev_count = curr_count;    }     // Till now we have covered 'prev_count' numbers     // Finding ith digit at ith place    for (int i = 1; i <= len; i++) {        // j = 1 means 2 j = 2 means ...j = 4 means 7        for (long long j = 1; j <= 4; j++) {            // if prev_count + 4 ^ (len-i) is less            // than n, increase prev_count by 4^(x-i)            if (prev_count + pow(4, len - i) < n)                prev_count += pow(4, len - i);             // else print the ith digit and break            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;            }        }    }    cout << endl;} // Driver functionint main(){    nthprimedigitsnumber(10);    nthprimedigitsnumber(21);    return 0;}
// Java implementation for finding nth number// made of prime digits only import static java.lang.Math.pow; class Test {     // Prints n-th number where each digit is a    // prime number    static void nthprimedigitsnumber(long n)    {        // Finding the length of n-th number        long len = 1;         // Count of numbers with len-1 digits        long prev_count = 0;        while (true) {            // Count of numbers with i digits            long curr_count = (long)(prev_count + pow(4, len));             // if i is the length of such number            // then n<4*(4^(i-1)-1)/3 and n>= 4*(4 ^ i-1)/3            // if a valid i is found break the loop            if (prev_count < n && curr_count >= n)                break;             // check for i + 1            len++;             prev_count = curr_count;        }         // Till now we have covered 'prev_count' numbers         // Finding ith digit at ith place        for (int i = 1; i <= len; i++) {            // j = 1 means 2 j = 2 means ...j = 4 means 7            for (long j = 1; j <= 4; j++) {                // if prev_count + 4 ^ (len-i) is less                // than n, increase prev_count by 4^(x-i)                if (prev_count + pow(4, len - i) < n)                    prev_count += pow(4, len - i);                 // else print the ith digit and break                else {                    if (j == 1)                        System.out.print("2");                    else if (j == 2)                        System.out.print("3");                    else if (j == 3)                        System.out.print("5");                    else if (j == 4)                        System.out.print("7");                    break;                }            }        }        System.out.println();    }     // Driver method    public static void main(String args[])    {        nthprimedigitsnumber(10);        nthprimedigitsnumber(21);    }}
# Python3 implementation for# finding nth number made of# prime digits onlyimport math # Prints n-th number where# each digit is a prime numberdef nthprimedigitsnumber(n):         # Finding the length    # of n-th number    len = 1;     # Count of numbers    # with len-1 digits    prev_count = 0;    while(1):                 # Count of numbers        # with i digits        curr_count = (prev_count +                      math.pow(4, len));         # if i is the length of such        # number then n<4*(4^(i-1)-1)/3        # and n>= 4*(4 ^ i-1)/3 if a valid        # i is found break the loop        if (prev_count < n and            curr_count >= n):            break;         # check for i + 1        len += 1;         prev_count = curr_count;     # Till now we have covered    # 'prev_count' numbers     # Finding ith digit at ith place    for i in range (1, len + 1):                 # j = 1 means 2 j = 2        # means ...j = 4 means 7        for j in range(1, 5):                         # if prev_count + 4 ^ (len-i)            # is less than n, increase            # prev_count by 4^(x-i)            if (prev_count + pow(4, len - i) < n):                prev_count += pow(4, len - i);             # else print the ith            # digit and break            else:                if (j == 1):                    print("2", end = "");                else if (j == 2):                    print("3", end = "");                else if (j == 3):                    print("5", end = "");                else if (j == 4):                    print("7", end = "");                break;    print(); # Driver Codenthprimedigitsnumber(10);nthprimedigitsnumber(21); # This code is contributed by mits
// C# implementation for finding nth// number made of prime digits onlyusing System; public class GFG {         // Prints n-th number where each    // digit is a prime number    static void nthprimedigitsnumber(long n)    {        // Finding the length of n-th number        long len = 1;         // Count of numbers with len-1 digits        long prev_count = 0;        while (true) {                         // Count of numbers with i digits            long curr_count = (long)(prev_count +                               Math.Pow(4, len));             // if i is the length of such number            // then n<4*(4^(i-1)-1)/3 and n>= 4*(4 ^ i-1)/3            // if a valid i is found break the loop            if (prev_count < n && curr_count >= n)                break;             // check for i + 1            len++;             prev_count = curr_count;        }         // Till now we have covered 'prev_count' numbers         // Finding ith digit at ith place        for (int i = 1; i <= len; i++) {                         // j = 1 means 2 j = 2 means ...j = 4 means 7            for (long j = 1; j <= 4; j++) {                                 // if prev_count + 4 ^ (len-i) is less                // than n, increase prev_count by 4^(x-i)                if (prev_count + Math.Pow(4, len - i) < n)                    prev_count += (long)Math.Pow(4, len - i);                 // else print the ith digit and break                else {                    if (j == 1)                        Console.Write("2");                    else if (j == 2)                        Console.Write("3");                    else if (j == 3)                        Console.Write("5");                    else if (j == 4)                        Console.Write("7");                    break;                }            }        }        Console.WriteLine();    }     // Driver method    public static void Main()    {        nthprimedigitsnumber(10);        nthprimedigitsnumber(21);    }} // This code is contributed by Sam007
<?php// PHP implementation for finding// nth number made of prime digits only // Prints n-th number where// each digit is a prime numberfunction nthprimedigitsnumber($n){    // Finding the length    // of n-th number    $len = 1;     // Count of numbers    // with len-1 digits    $prev_count = 0;    while (true)    {        // Count of numbers        // with i digits        $curr_count = $prev_count +                      pow(4, $len);         // if i is the length of such        // number then n<4*(4^(i-1)-1)/3        // and n>= 4*(4 ^ i-1)/3 if a valid        // i is found break the loop        if ($prev_count < $n &&            $curr_count >= $n)            break;         // check for i + 1        $len++;         $prev_count = $curr_count;    }     // Till now we have covered    // 'prev_count' numbers     // Finding ith digit at ith place    for ($i = 1; $i <= $len; $i++)    {        // j = 1 means 2 j = 2        // means ...j = 4 means 7        for ($j = 1; $j <= 4; $j++)        {            // if prev_count + 4 ^ (len-i)            // is less than n, increase            // prev_count by 4^(x-i)            if ($prev_count +                 pow(4, $len - $i) < $n)                $prev_count += pow(4, $len - $i);             // else print the ith            // digit and break            else            {                if ($j == 1)                    echo "2";                else if ($j == 2)                    echo "3";                else if ($j == 3)                    echo "5";                else if ($j == 4)                    echo "7";                break;            }        }    }     echo "\n";} // Driver Codenthprimedigitsnumber(10);nthprimedigitsnumber(21); // This code is contributed by ajit?>
<script> // javascript implementation for finding nth number// made of prime digits only  // Prints n-th number where each digit is a// prime numberfunction nthprimedigitsnumber(n){    // Finding the length of n-th number    var len = 1;     // Count of numbers with len-1 digits    var prev_count = 0;    while (true) {        // Count of numbers with i digits        var curr_count = (prev_count + Math.pow(4, len));         // if i is the length of such number        // then n<4*(4^(i-1)-1)/3 and n>= 4*(4 ^ i-1)/3        // if a valid i is found break the loop        if (prev_count < n && curr_count >= n)            break;         // check for i + 1        len++;         prev_count = curr_count;    }     // Till now we have covered 'prev_count' numbers     // Finding ith digit at ith place    for (var i = 1; i <= len; i++) {        // j = 1 means 2 j = 2 means ...j = 4 means 7        for (var j = 1; j <= 4; j++) {            // if prev_count + 4 ^ (len-i) is less            // than n, increase prev_count by 4^(x-i)            if (prev_count + Math.pow(4, len - i) < n)                prev_count += Math.pow(4, len - i);             // else print the ith digit and break            else {                if (j == 1)                    document.write("2");                else if (j == 2)                    document.write("3");                else if (j == 3)                    document.write("5");                else if (j == 4)                    document.write("7");                break;            }        }    }    document.write('<br>');} // Driver methodnthprimedigitsnumber(10);nthprimedigitsnumber(21); // This code is contributed by Amit Katiyar</script>
Output :  
33
222
Alternate Solution (Works in O(Log n) 
In this post, a O(log n) solution is discussed 
which is based on below pattern in numbers. The 
numbers can be seen
                                  ""
      /                |                    |                 \
     2                 3                    5                  7
 / |  | \           / | |  \             /  | | \          /  | |  \ 
22 23 25 27        32 33 35 37         52 53 55 57        72 73 75 77
/||\/||\/||\/||\   /||\/||\/||\/||\   /||\/||\/||\/||\   /||\/||\/||\/||\

We can notice following :
1st. 5th, 9th. 13th, ..... numbers have 2 as last digit.
2nd. 6th, 10th. 14th, ..... numbers have 3 as last digit.
3nd. 7th, 11th. 15th, ..... numbers have 5 as last digit.
4th. 8th, 12th. 16th, ..... numbers have 7 as last digit.
 
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find n-th number with// prime digits 2, 3 and 7#include <algorithm>#include <iostream>#include <string>using namespace std; string nthprimedigitsnumber(int number){    int rem;    string num;    while (number) {        // remainder for check element position        rem = number % 4;        switch (rem) {         // if number is 1st position in tree        case 1:            num.push_back('2');            break;         // if number is 2nd position in tree        case 2:            num.push_back('3');            break;         // if number is 3rd position in tree        case 3:            num.push_back('5');            break;         // if number is 4th position in tree        case 0:            num.push_back('7');            break;        }         if (number % 4 == 0)           number--;         number = number / 4;    }    reverse(num.begin(), num.end());    return num;} // Driver codeint main(){    int number = 21;    cout << nthprimedigitsnumber(10) << "\n";    cout << nthprimedigitsnumber(21) << "\n";    return 0;}
// Java program to find n-th number with// prime digits 2, 3 and 7import java.util.*;class GFG{static String nthprimedigitsnumber(int number){    int rem;    String num="";    while (number>0) {        // remainder for check element position        rem = number % 4;        switch (rem) {         // if number is 1st position in tree        case 1:            num+='2';            break;         // if number is 2nd position in tree        case 2:            num+='3';            break;         // if number is 3rd position in tree        case 3:            num+='5';            break;         // if number is 4th position in tree        case 0:            num+='7';            break;        }        if (number % 4 == 0)           number--;         number = number / 4;    }         return new StringBuilder(num).reverse().toString();} // Driver codepublic static void main(String[] args){    int number = 21;    System.out.println(nthprimedigitsnumber(10));    System.out.println(nthprimedigitsnumber(21));}}// This code is contributed by mits
# Python3 program to find n-th number# with prime digits 2, 3 and 7def nthprimedigitsnumber(number):     num = "";    while (number > 0):                 # remainder for check element position        rem = number % 4;                 # if number is 1st position in tree        if (rem == 1):            num += '2';         # if number is 2nd position in tree        if (rem == 2):            num += '3';         # if number is 3rd position in tree        if (rem == 3):            num += '5';         # if number is 4th position in tree        if (rem == 0):            num += '7';         if (number % 4 == 0):            number = number - 1         number = number // 4;     return num[::-1]; # Driver codenumber = 21;print(nthprimedigitsnumber(10));print(nthprimedigitsnumber(number)); # This code is contributed by mits
// C# program to find n-th number with// prime digits 2, 3 and 7using System;class GFG{static string nthprimedigitsnumber(int number){    int rem;    string num="";    while (number>0) {        // remainder for check element position        rem = number % 4;        switch (rem) {         // if number is 1st position in tree        case 1:            num+='2';            break;         // if number is 2nd position in tree        case 2:            num+='3';            break;         // if number is 3rd position in tree        case 3:            num+='5';            break;         // if number is 4th position in tree        case 0:            num+='7';            break;        }        if (number % 4 == 0)           number--;         number = number / 4;    }    char[] st = num.ToCharArray();    Array.Reverse(st);    return new string(st);} // Driver codestatic void Main(){    int number = 21;    Console.WriteLine(nthprimedigitsnumber(10));    Console.WriteLine(nthprimedigitsnumber(number));}}// This code is contributed by mits
<?php// PHP program to find n-th number with// prime digits 2, 3 and 7 function nthprimedigitsnumber($number){    $num = "";    while ($number > 0)    {        // remainder for check element position        $rem = $number % 4;        switch ($rem)        {             // if number is 1st position in tree            case 1:                $num .= '2';                break;                 // if number is 2nd position in tree            case 2:                $num .= '3';                break;                 // if number is 3rd position in tree            case 3:                $num .= '5';                break;                 // if number is 4th position in tree            case 0:                $num .= '7';                break;        }        if ($number % 4 == 0)           $number--;         $number = (int)($number / 4);    }     return strrev($num);} // Driver code$number = 21;print(nthprimedigitsnumber(10) . "\n");print(nthprimedigitsnumber($number)); // This code is contributed by mits
<script>    // Javascript program to find n-th number with prime digits 2, 3 and 7         function nthprimedigitsnumber(number)    {        let rem;        let num="";        while (number>0) {            // remainder for check element position            rem = number % 4;            switch (rem) {             // if number is 1st position in tree            case 1:                num+='2';                break;             // if number is 2nd position in tree            case 2:                num+='3';                break;             // if number is 3rd position in tree            case 3:                num+='5';                break;             // if number is 4th position in tree            case 0:                num+='7';                break;            }            if (number % 4 == 0)               number--;             number = parseInt(number / 4, 10);        }        let st = num.split('');        st.reverse();        return (st.join(""));    }         let number = 21;    document.write(nthprimedigitsnumber(10) + "</br>");    document.write(nthprimedigitsnumber(number)); </script>
Output :  
33
222
This article is contributed by Ayush Jha and Devanshu agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
Sam007
jit_t
Mithun Kumar
Abhishek_Vashisht
one96
suresh07
amit143katiyar
arorakashish0911
simmytarika5
Prime Number
Arrays
Mathematical
Arrays
Mathematical
Prime Number
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Linked List vs Array
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7