📌  相关文章
📜  计算数字总和等于素数的 N 位数字

📅  最后修改于: 2021-09-22 10:37:28             🧑  作者: Mango

给定一个正整数N ,任务是计算数字之和为素数N位数字的数量

例子:

朴素方法:解决给定问题的最简单方法是生成所有可能的 N 位数字并计算那些数字之和为素数的数字。检查所有数字后,打印计数值作为结果的总数字计数。

时间复杂度: O(N *10 N )

高效方法:上述方法也可以通过使用递归动态规划来优化,因为上述问题具有重叠子问题最优子结构。请按照以下步骤解决问题:

  • 初始化一个全局二维数组dp[N+1][N*10] ,所有值都为-1 ,用于存储每个递归调用的结果。
  • 使用埃拉托色尼筛法计算最多(N * 10)个数的素数。
  • 通过执行以下步骤定义一个递归函数,比如countOfNumbers(index, sum, N)
    • 如果索引的值为N+1
      • 如果和是数,则返回1作为有效的N位数字已形成。
      • 否则返回0
    • 如果已经计算了状态dp[index][sum]的结果,则返回该值dp[index][sum]。
    • 如果当前索引为1 ,则可以放置[1-9] 中的任何数字,否则可以放置[0-9]
    • 正确放置数字后, 下一个索引递归调用countOfNumbers函数并将所有递归未决结果汇总到变量val 中
    • val的值存入dp[index][sum]表的当前状态。
    • 将此状态的结果 val 返回给它的父递归调用。
  • 打印函数countOfNumbers(1, 0, N)返回的值作为结果。

下面是上述方法的实现:

C++
#include 
using namespace std;
 
// Stores the dp states
int dp[100][1000];
 
// Check if a number is
// a prime or not
bool prime[1005];
 
// Function to generate all prime numbers
// that are less than or equal to n
void SieveOfEratosthenes(int n)
{
    // Base cases.
    prime[0] = prime[1] = false;
    for (int p = 2; p * p <= n; p++) {
 
        // If prime[p] is not changed,
        // then it is a prime
        if (prime[p] == true) {
 
            // Update all multiples
            // of as non-prime
            for (int i = p * p; i <= n; i += p)
                prime[i] = false;
        }
    }
}
 
// Function to find the count of N-digit numbers
// such that the sum of digits is a prime number
int countOfNumbers(int index, int sum, int N)
{
 
    // If end of array is reached
    if (index == N + 1) {
 
        // If the sum is equal to a prime number
        if (prime[sum] == true) {
            return 1;
        }
 
        // Otherwise
        return 0;
    }
 
    int& val = dp[index][sum];
 
    // If the dp-states are already computed
    if (val != -1) {
 
        return val;
    }
 
    val = 0;
 
    // If index = 1, any digit from [1 - 9] can be placed.
    // If N = 1, 0 also can be placed.
    if (index == 1) {
 
        for (int digit = (N == 1 ? 0 : 1); digit <= 9;
             ++digit) {
            val += countOfNumbers(index + 1, sum + digit,
                                  N);
        }
    }
 
    // Otherwise, any digit from [0 - 9] can be placed.
    else {
        for (int digit = 0; digit <= 9; ++digit) {
            val += countOfNumbers(index + 1, sum + digit,
                                  N);
        }
    }
 
    // Return the answer.
    return val;
}
 
// Driver Code
int main()
{
    // Initializing dp array with -1
    memset(dp, -1, sizeof dp);
 
    // Initializing prime array to true
    memset(prime, true, sizeof(prime));
 
    // Find all primes less than or equal to 1000,
    // which is sufficient for N upto 100
    SieveOfEratosthenes(1000);
 
    // Given Input
    int N = 6;
 
    // Function call
    cout << countOfNumbers(1, 0, N);
 
    return 0;
}


Java
import java.util.Arrays;
 
class GFG{
 
// Stores the dp states
public static int[][] dp = new int[100][1000];
 
// Check if a number is
// a prime or not
public static boolean[] prime = new boolean[1005];
 
// Function to generate all prime numbers
// that are less than or equal to n
public static void SieveOfEratosthenes(int n)
{
     
    // Base cases.
    prime[0] = prime[1] = false;
    for(int p = 2; p * p <= n; p++)
    {
         
        // If prime[p] is not changed,
        // then it is a prime
        if (prime[p] == true)
        {
             
            // Update all multiples
            // of as non-prime
            for(int i = p * p; i <= n; i += p)
                prime[i] = false;
        }
    }
}
 
// Function to find the count of N-digit numbers
// such that the sum of digits is a prime number
public static int countOfNumbers(int index, int sum,
                                 int N)
{
     
    // If end of array is reached
    if (index == N + 1)
    {
         
        // If the sum is equal to a prime number
        if (prime[sum] == true)
        {
            return 1;
        }
 
        // Otherwise
        return 0;
    }
 
    int val = dp[index][sum];
 
    // If the dp-states are already computed
    if (val != -1)
    {
        return val;
    }
 
    val = 0;
 
    // If index = 1, any digit from [1 - 9] can be placed.
    // If N = 1, 0 also can be placed.
    if (index == 1)
    {
        for(int digit = (N == 1 ? 0 : 1);
                digit <= 9; ++digit)
        {
            val += countOfNumbers(index + 1,
                                    sum + digit, N);
        }
    }
 
    // Otherwise, any digit from [0 - 9] can be placed.
    else
    {
        for(int digit = 0; digit <= 9; ++digit)
        {
            val += countOfNumbers(index + 1,
                                    sum + digit, N);
        }
    }
 
    // Return the answer.
    return val;
}
 
// Driver Code
public static void main(String args[])
{
     
    // Initializing dp array with -1
    for(int[] row : dp)
        Arrays.fill(row, -1);
 
    // Initializing prime array to true
    Arrays.fill(prime, true);
 
    // Find all primes less than or equal to 1000,
    // which is sufficient for N upto 100
    SieveOfEratosthenes(1000);
 
    // Given Input
    int N = 6;
 
    // Function call
    System.out.println(countOfNumbers(1, 0, N));
}
}
 
// This code is contributed by gfgking


Javascript


输出:
222638

时间复杂度: O(N 2 * 10)
辅助空间: O(N 2 )

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程