📜  给定范围内的数字分别在素数和非素数位置具有素数和非素数

📅  最后修改于: 2021-04-27 21:40:05             🧑  作者: Mango

给定两个整数LR ,任务是查找在[L,R]范围内具有素数位在素数位置和非素数在非素数位置的数字计数。

例子:

天真的方法:解决问题的最简单方法是在[L,R]范围内进行迭代。对于每个i数字,请检查数字的数字是否在素数位置上是质数,而在非素数位置上不是质数。如果发现为真,则增加计数。最后,打印获得的计数。

时间复杂度: O(R – L +1)* sqrt(R)* log 10 (R)
辅助空间: O(1)

高效方法:为了优化上述方法,想法是使用Digit DP。以下是动态编程状态之间的递归关系:

请按照以下步骤解决问题:

  • 初始化一个4D数组,例如dp [pos] [st] [tight] [prime]
  • 使用记忆(例如cntR)计算数字Rdp [pos] [st] [tight] [prime]的值。
  • cntL表示,用记忆计算L – 1dp [pos] [st] [tight] [prime]的值。
  • 最后,打印(cntR – cntL)的值。

下面是上述方法的实现:

C++14
// C++ program for the above approach
 
#include 
using namespace std;
 
// Store digits of a number
vector num;
 
// Store overlapping subproblems
long long int dp[19][2][2][19];
 
// Function to check if a
// number is prime or not
bool isPrime(long long int n)
{
 
    // If n is less than
    // or equal to 1
    if (n <= 1)
        return false;
 
    // If n is less than
    // or equal to 3
    if (n <= 3)
        return true;
 
    // If n is a multiple of 2 or 3
    if (n % 2 == 0 || n % 3 == 0)
        return false;
 
    // Iterate over the range [5, n]
    for (long long int i = 5; i * i <= n;
         i = i + 6) {
 
        // If n is a multiple of i or (i + 2)
        if (n % i == 0 || n % (i + 2) == 0)
            return false;
    }
 
    return true;
}
 
// Function to count the required
// numbers from the given range
long long cntNum(long long pos, long long st,
                 long long tight, long long prime)
{
 
    // Base Case
    if (pos == num.size())
        return 1;
 
    // If the subproblems already computed
    if (dp[pos][st][tight][prime] != -1)
        return dp[pos][st][tight][prime];
 
    long long int res = 0;
 
    // Stores maximum possible
    // at current digits
    long long end = (tight == 0) ? num[pos] : 9;
 
    // Iterate over all possible digits
    // at current position
    for (long long i = 0; i <= end; i++) {
 
        // Check if i is the maximum possible
        // digit at current position or not
        long long ntight = (i < end) ? 1 : tight;
 
        // Check if a number contains
        // leading 0s or not
        long long int nzero = (i != 0) ? 1 : st;
 
        // If number has only leading zeros
        // and digit is non-zero
        if ((nzero == 1) && isPrime(i) && isPrime(prime)) {
 
            // Prime digits at prime positions
            res += cntNum(pos + 1, nzero,
                          ntight, prime + 1);
        }
 
        if ((nzero == 1) && !isPrime(i) && !isPrime(prime)) {
 
            // Non-prime digits at
            // non-prime positions
            res += cntNum(pos + 1, nzero,
                          ntight, prime + 1);
        }
 
        // If the number has only leading zeros
        // and i is zero,
        if (nzero == 0)
            res += cntNum(pos + 1, nzero,
                          ntight, prime);
    }
    return dp[pos][st][tight][prime] = res;
}
 
// Function to find count of numbers in
// range [0, b] whose digits are prime
// at prime and non-prime at non-prime pos
long long int cntZeroRange(long long int b)
{
 
    num.clear();
 
    // Insert digits of a number, b
    while (b > 0) {
        num.push_back(b % 10);
        b /= 10;
    }
 
    // Reversing the digits in num
    reverse(num.begin(), num.end());
 
    // Initializing dp with -1
    memset(dp, -1, sizeof(dp));
 
    long long int res = cntNum(0, 0, 0, 1);
 
    // Returning the value
    return res;
}
 
// Driver Code
int main()
{
 
    // Given range, [L, R]
    long long int L = 5, R = 22;
 
    // Function Call
    long long int res
        = cntZeroRange(R) - cntZeroRange(L - 1);
 
    // Print answer
    cout << res << endl;
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
class GFG
{
 
// Store digits of a number
static Vector num = new Vector<>();
 
// Store overlapping subproblems
static int [][][][]dp = new int[19][2][2][19];
 
// Function to check if a
// number is prime or not
static boolean isPrime(int n)
{
 
    // If n is less than
    // or equal to 1
    if (n <= 1)
        return false;
 
    // If n is less than
    // or equal to 3
    if (n <= 3)
        return true;
 
    // If n is a multiple of 2 or 3
    if (n % 2 == 0 || n % 3 == 0)
        return false;
 
    // Iterate over the range [5, n]
    for (int i = 5; i * i <= n;
         i = i + 6) {
 
        // If n is a multiple of i or (i + 2)
        if (n % i == 0 || n % (i + 2) == 0)
            return false;
    }
    return true;
}
 
// Function to count the required
// numbers from the given range
static int cntNum(int pos, int st,
                 int tight, int prime)
{
 
    // Base Case
    if (pos == num.size())
        return 1;
 
    // If the subproblems already computed
    if (dp[pos][st][tight][prime] != -1)
        return dp[pos][st][tight][prime];
    int res = 0;
 
    // Stores maximum possible
    // at current digits
    int end = (tight == 0) ? num.get(pos) : 9;
 
    // Iterate over all possible digits
    // at current position
    for (int i = 0; i <= end; i++)
    {
 
        // Check if i is the maximum possible
        // digit at current position or not
        int ntight = (i < end) ? 1 : tight;
 
        // Check if a number contains
        // leading 0s or not
        int nzero = (i != 0) ? 1 : st;
 
        // If number has only leading zeros
        // and digit is non-zero
        if ((nzero == 1) && isPrime(i) && isPrime(prime)) {
 
            // Prime digits at prime positions
            res += cntNum(pos + 1, nzero,
                          ntight, prime + 1);
        }
 
        if ((nzero == 1) && !isPrime(i) && !isPrime(prime)) {
 
            // Non-prime digits at
            // non-prime positions
            res += cntNum(pos + 1, nzero,
                          ntight, prime + 1);
        }
 
        // If the number has only leading zeros
        // and i is zero,
        if (nzero == 0)
            res += cntNum(pos + 1, nzero,
                          ntight, prime);
    }
    return dp[pos][st][tight][prime] = res;
}
 
// Function to find count of numbers in
// range [0, b] whose digits are prime
// at prime and non-prime at non-prime pos
static int cntZeroRange(int b)
{
 
    num.clear();
 
    // Insert digits of a number, b
    while (b > 0) {
        num.add(b % 10);
        b /= 10;
    }
 
    // Reversing the digits in num
    Collections.reverse(num);
 
    // Initializing dp with -1
    for (int i = 0; i < 19; i++)
         for (int j = 0; j < 2; j++)
             for (int k = 0; k < 2; k++)
                 for (int l = 0; l < 19; l++)
                     dp[i][j][k][l] = -1;
 
    int res = cntNum(0, 0, 0, 1);
 
    // Returning the value
    return res;
}
 
// Driver Code
public static void main(String[] args)
{
 
    // Given range, [L, R]
    int L = 5, R = 22;
 
    // Function Call
    int res
        = cntZeroRange(R) - cntZeroRange(L - 1);
 
    // Print answer
    System.out.print(res +"\n");
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 program for the above approach
from math import ceil, sqrt
 
# Function to check if a
# number is prime or not
def isPrime(n):
     
    # If n is less than
    # or equal to 1
    if (n <= 1):
        return False
 
    # If n is less than
    # or equal to 3
    if (n <= 3):
        return True
 
    # If n is a multiple of 2 or 3
    if (n % 2 == 0 or n % 3 == 0):
        return False
 
    # Iterate over the range [5, n]
    for i in range(5, ceil(sqrt(n)), 6):
         
        # If n is a multiple of i or (i + 2)
        if (n % i == 0 or n % (i + 2) == 0):
            return False
 
    return True
 
# Function to count the required
# numbers from the given range
def cntNum(pos, st, tight, prime):
     
    global dp, num
     
    if (pos == len(num)):
        return 1
 
    # If the subproblems already computed
    if (dp[pos][st][tight][prime] != -1):
        return dp[pos][st][tight][prime]
 
    res = 0
 
    # Stores maximum possible
    # at current digits
    end = num[pos] if (tight == 0) else  9
 
    # Iterate over all possible digits
    # at current position
    for i in range(end + 1):
         
        # Check if i is the maximum possible
        # digit at current position or not
        ntight = 1 if (i < end) else tight
 
        # Check if a number contains
        # leading 0s or not
        nzero = 1 if (i != 0) else st
 
        # If number has only leading zeros
        # and digit is non-zero
        if ((nzero == 1) and isPrime(i) and
                             isPrime(prime)):
                                  
            # Prime digits at prime positions
            res += cntNum(pos + 1, nzero, ntight,
                        prime + 1)
 
        if ((nzero == 1) and isPrime(i) == False and
                         isPrime(prime) == False):
 
            # Non-prime digits at
            # non-prime positions
            res += cntNum(pos + 1, nzero, ntight,
                        prime + 1)
 
        # If the number has only leading zeros
        # and i is zero,
        if (nzero == 0):
            res += cntNum(pos + 1, nzero,
                          ntight, prime)
                           
    dp[pos][st][tight][prime] = res
     
    return dp[pos][st][tight][prime]
 
# Function to find count of numbers in
# range [0, b] whose digits are prime
# at prime and non-prime at non-prime pos
def cntZeroRange(b):
     
    global num, dp
 
    num.clear()
     
    while (b > 0):
        num.append(b % 10)
        b //= 10
 
    # Reversing the digits in num
    num = num[::-1]
 
    # print(num)
    dp = [[[[-1 for i in range(19)]
                for i in range(2)]
                for i in range(2)]
                for i in range(19)]
 
    res = cntNum(0, 0, 0, 1)
 
    # Returning the value
    return res
 
# Driver Code
if __name__ == '__main__':
 
    dp = [[[[-1 for i in range(19)]
                for i in range(2)]
                for i in range(2)]
                for i in range(19)]
    L, R, num = 5, 22, []
 
    # Function Call
    res = cntZeroRange(R) - cntZeroRange(L - 1)
 
    # Print answer
    print(res)
 
# This code is contributed by mohit kumar 29


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG
{
 
  // Store digits of a number
  static List num = new List();
 
  // Store overlapping subproblems
  static int[, , , ] dp = new int[19, 2, 2, 19];
 
  // Function to check if a
  // number is prime or not
  static bool isPrime(int n)
  {
 
    // If n is less than
    // or equal to 1
    if (n <= 1)
      return false;
 
    // If n is less than
    // or equal to 3
    if (n <= 3)
      return true;
 
    // If n is a multiple of 2 or 3
    if (n % 2 == 0 || n % 3 == 0)
      return false;
 
    // Iterate over the range [5, n]
    for (int i = 5; i * i <= n; i = i + 6) {
 
      // If n is a multiple of i or (i + 2)
      if (n % i == 0 || n % (i + 2) == 0)
        return false;
    }
    return true;
  }
 
  // Function to count the required
  // numbers from the given range
  static int cntNum(int pos, int st, int tight, int prime)
  {
 
    // Base Case
    if (pos == num.Count)
      return 1;
 
    // If the subproblems already computed
    if (dp[pos, st, tight, prime] != -1)
      return dp[pos, st, tight, prime];
    int res = 0;
 
    // Stores maximum possible
    // at current digits
    int end = (tight == 0) ? num[pos] : 9;
 
    // Iterate over all possible digits
    // at current position
    for (int i = 0; i <= end; i++) {
 
      // Check if i is the maximum possible
      // digit at current position or not
      int ntight = (i < end) ? 1 : tight;
 
      // Check if a number contains
      // leading 0s or not
      int nzero = (i != 0) ? 1 : st;
 
      // If number has only leading zeros
      // and digit is non-zero
      if ((nzero == 1) && isPrime(i)
          && isPrime(prime)) {
 
        // Prime digits at prime positions
        res += cntNum(pos + 1, nzero, ntight,
                      prime + 1);
      }
 
      if ((nzero == 1) && !isPrime(i)
          && !isPrime(prime)) {
 
        // Non-prime digits at
        // non-prime positions
        res += cntNum(pos + 1, nzero, ntight,
                      prime + 1);
      }
 
      // If the number has only leading zeros
      // and i is zero,
      if (nzero == 0)
        res += cntNum(pos + 1, nzero, ntight,
                      prime);
    }
    return dp[pos, st, tight, prime] = res;
  }
 
  // Function to find count of numbers in
  // range [0, b] whose digits are prime
  // at prime and non-prime at non-prime pos
  static int cntZeroRange(int b)
  {
 
    num.Clear();
 
    // Insert digits of a number, b
    while (b > 0) {
      num.Add(b % 10);
      b /= 10;
    }
 
    // Reversing the digits in num
    num.Reverse();
 
    // Initializing dp with -1
    for (int i = 0; i < 19; i++)
      for (int j = 0; j < 2; j++)
        for (int k = 0; k < 2; k++)
          for (int l = 0; l < 19; l++)
            dp[i, j, k, l] = -1;
 
    int res = cntNum(0, 0, 0, 1);
 
    // Returning the value
    return res;
  }
 
  // Driver Code
  public static void Main(string[] args)
  {
 
    // Given range, [L, R]
    int L = 5, R = 22;
 
    // Function Call
    int res = cntZeroRange(R) - cntZeroRange(L - 1);
 
    // Print answer
    Console.WriteLine(res + "\n");
  }
}
 
// This code is contributed by chitranayal.


输出:
7

时间复杂度: O(log 10 (R)* log 10 (L)sqrt(log 10 (R))* 10 * 4))
辅助空间: O(log 10 (R)* log 10 (L)* 4)