📜  仅查找由质数(2、3、5和7)组成的第n个数字

📅  最后修改于: 2021-04-27 23:49:10             🧑  作者: Mango

给定数字“ n”,我们需要找到第n个数字,每个数字都是质数,即2、3、5、7…。换句话说,您必须找到此序列的第n个数字。 2、3、5、5、22、23……
假设找到的第n个数字小于等于10 ^ 18
例子 :

Input  : 10
Output : 33
         2, 3, 5, 7, 22, 23, 25, 
         27, 32, 33

Input  : 21
Output : 222

有四个素数2、3、5和7。第一个观察结果是x长度和由素数组成的数为4^x因为对于每个职位您都有4个选择,所以总数为4 ^ x。
因此,长度为1到len(即2或3或更大)的此类数字的总数为4 *((4 len – 1)/ 3)。 (这是第一项为4且公共比率为4的GP的总和)

该算法主要分为两个步骤。

  1. 通过上面的观察,我们找到了第n个数字中的位数。我们从len = 0开始,并在它的值小于4 *((4 len – 1)/ 3)时继续递增。
  2. 现在我们知道第n个数字中的位数。我们还知道具有(len-1)个数字的数字计数。将此计数设为“ prev_count”。现在我们一一找到结果中的数字。在第i个位置的第一个定位2(假设到i-1的所有位置都已满),我们有4 ^(len – i)个可能的数字,并检查2是否是正确的候选者,然后检查后面是否有数字计数放置2是否大于或等于n。如果为真,则2是正确的候选者;如果不为真,则意味着如果将2固定在第i个位置,则只能覆盖prev_count + 4 ^(len-i)个数字。因此,将prev_count增加4 ^(len-i)并重复此步骤3,检查3是否在第i个位置合适。如果不适合5,如果不适合5,则适合7。保证7将适合如果2、3和5不适合,则适合它,因为我们确定该数字的第n个长度仅为len。

以下是上述步骤的实现。

C/C++
// C++ implementation for finding nth number
// made of prime digits only
#include 
using namespace std;
  
// Prints n-th number where each digit is a
// prime number
void 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 function
int main()
{
    nthprimedigitsnumber(10);
    nthprimedigitsnumber(21);
    return 0;
}


Java
// 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
# Python3 implementation for 
# finding nth number made of
# prime digits only
import math
  
# Prints n-th number where 
# each digit is a prime number
def 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 = "");
                elif (j == 2):
                    print("3", end = "");
                elif (j == 3):
                    print("5", end = "");
                elif (j == 4):
                    print("7", end = "");
                break;
    print();
  
# Driver Code
nthprimedigitsnumber(10);
nthprimedigitsnumber(21);
  
# This code is contributed by mits


C#
// C# implementation for finding nth 
// number made of prime digits only
using 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
= 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 Code
nthprimedigitsnumber(10);
nthprimedigitsnumber(21);
  
// This code is contributed by ajit
?>


C++
// CPP program to find n-th number with
// prime digits 2, 3 and 7
#include 
#include 
#include 
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 code
int main()
{
    int number = 21;
    cout << nthprimedigitsnumber(10) << "\n";
    cout << nthprimedigitsnumber(21) << "\n";
    return 0;
}


Java
// Java program to find n-th number with 
// prime digits 2, 3 and 7 
import 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 code 
public 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
# Python3 program to find n-th number 
# with prime digits 2, 3 and 7 
def 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 code 
number = 21; 
print(nthprimedigitsnumber(10)); 
print(nthprimedigitsnumber(number)); 
  
# This code is contributed by mits


C#
// C# program to find n-th number with 
// prime digits 2, 3 and 7 
using 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 code 
static void Main() 
{ 
    int number = 21; 
    Console.WriteLine(nthprimedigitsnumber(10)); 
    Console.WriteLine(nthprimedigitsnumber(number)); 
} 
}
// This code is contributed by mits


PHP
 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


输出 :

33
222

替代解决方案(适用于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++

// CPP program to find n-th number with
// prime digits 2, 3 and 7
#include 
#include 
#include 
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 code
int main()
{
    int number = 21;
    cout << nthprimedigitsnumber(10) << "\n";
    cout << nthprimedigitsnumber(21) << "\n";
    return 0;
}

Java

// Java program to find n-th number with 
// prime digits 2, 3 and 7 
import 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 code 
public 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

# Python3 program to find n-th number 
# with prime digits 2, 3 and 7 
def 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 code 
number = 21; 
print(nthprimedigitsnumber(10)); 
print(nthprimedigitsnumber(number)); 
  
# This code is contributed by mits

C#

// C# program to find n-th number with 
// prime digits 2, 3 and 7 
using 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 code 
static void Main() 
{ 
    int number = 21; 
    Console.WriteLine(nthprimedigitsnumber(10)); 
    Console.WriteLine(nthprimedigitsnumber(number)); 
} 
}
// This code is contributed by mits

的PHP

 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

输出 :

33
222