📌  相关文章
📜  查询数字总和为质数的范围内的回文数

📅  最后修改于: 2021-04-17 14:07:13             🧑  作者: Mango

给定一个由N个形式为{L,R}的查询组成的数组Q [] [] ,每个查询的任务是查找回文数在[L,R]范围内的数字的计数及其总和。数字是质数。

例子:

幼稚的方法:解决给定问题的最简单方法是在每个查询的范围[L,R]上进行迭代并打印回文数的计数,其总和为质数。

时间复杂度: O(N *(R – L))
辅助空间: O(1)

高效的方法:可以通过使用“包含-排除”原理和前缀和的概念来优化上述方法。请按照以下步骤解决给定的问题:

  • 初始化数组arr []来存储直到回文索引i为止的数字计数,并且它们的数字之和是每个i索引处的质数。
  • 迭代[ 1,10 5 ]范围,对于每个元素X ,如果数字X是回文数,并且数字的总和为质数,则将arr [i]更新为1 。否则,设置arr [i] = 0
  • 找到数组arr []的前缀和数组。
  • 现在,遍历数组Q [] ,对于每个查询{L,R} ,打印范围为[L,R]的回文数的总计数,并且它们的数字之和为质数,如(arr [ R] – arr [L – 1])

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
int arr[100005];
 
// Function to check if the number N
// is palindrome or not
bool isPalindrome(int N)
{
    // Store the value of N
    int temp = N;
 
    // Store the reverse of number N
    int res = 0;
 
    // Reverse temp and store in res
    while (temp != 0) {
        int rem = temp % 10;
        res = res * 10 + rem;
        temp /= 10;
    }
 
    // If N is the same as res, then
    // return true
    if (res == N) {
        return true;
    }
    else {
        return false;
    }
}
 
// Function to find the sum of the
// digits of the number N
int sumOfDigits(int N)
{
    // Stores the sum of the digits
    int sum = 0;
 
    while (N != 0) {
        // Add the last digit of the
        // number N to the sum
        sum += N % 10;
 
        // Remove the last digit
        // from N
        N /= 10;
    }
 
    // Return the resultant sum
    return sum;
}
 
// Function to check if N is prime or not
bool isPrime(int n)
{
    // If i is 1 or 0, then return false
    if (n <= 1) {
        return false;
    }
 
    // Check if i is divisible by any
    // number in the range [2, n/2]
    for (int i = 2; i <= n / 2; ++i) {
        // If n is divisible by i
        if (n % i == 0)
            return false;
    }
 
    return true;
}
 
// Function to precompute all the numbers
// till 10^5 that are palindromic and
// whose sum of digits is prime numbers
void precompute()
{
    // Iterate over the range 1 to 10 ^ 5
    for (int i = 1; i <= 100000; i++) {
 
        // If i is a palindrome number
        if (isPalindrome(i)) {
 
            // Stores the sum of
            // the digits in i
            int sum = sumOfDigits(i);
 
            // If the sum of digits
            // in i is a prime number
            if (isPrime(sum))
                arr[i] = 1;
            else
                arr[i] = 0;
        }
        else
            arr[i] = 0;
    }
 
    // Find the prefix sum of arr[]
    for (int i = 1; i <= 100000; i++) {
        arr[i] = arr[i] + arr[i - 1];
    }
}
 
// Function to count all the numbers in
// the given ranges that are palindromic
// and the sum of digits is prime numbers
void countNumbers(int Q[][2], int N)
{
 
    // Function Call to precompute
    // all the numbers till 10^5
    precompute();
 
    // Traverse the given queries Q[]
    for (int i = 0; i < N; i++) {
 
        // Print the result for
        // each query
        cout << (arr[Q[i][1]]
                 - arr[Q[i][0] - 1]);
        cout << endl;
    }
}
 
// Driver Code
int main()
{
    int Q[][2] = { { 5, 9 }, { 1, 101 } };
    int N = sizeof(Q) / sizeof(Q[0]);
 
    // Function Call
    countNumbers(Q, N);
}


Java
// Java program for the above approach
class GFG{
     
static int[] arr = new int[100005];
 
// Function to check if the number N
// is palindrome or not
static boolean isPalindrome(int N)
{
    int temp = N;
 
    // Store the reverse of number N
    int res = 0;
 
    // Reverse temp and store in res
    while (temp != 0)
    {
        int rem = temp % 10;
        res = res * 10 + rem;
        temp /= 10;
    }
 
    // If N is the same as res, then
    // return true
    if (res == N)
    {
        return true;
    }
    else
    {
        return false;
    }
}
 
// Function to find the sum of the
// digits of the number N
static int sumOfDigits(int N)
{
     
    // Stores the sum of the digits
    int sum = 0;
 
    while (N != 0)
    {
         
        // Add the last digit of the
        // number N to the sum
        sum += N % 10;
 
        // Remove the last digit
        // from N
        N /= 10;
    }
 
    // Return the resultant sum
    return sum;
}
 
// Function to check if N is prime or not
static boolean isPrime(int n)
{
    // If i is 1 or 0, then return false
    if (n <= 1)
    {
        return false;
    }
 
    // Check if i is divisible by any
    // number in the range [2, n/2]
    for(int i = 2; i <= n / 2; ++i)
    {
         
        // If n is divisible by i
        if (n % i == 0)
            return false;
    }
    return true;
}
 
// Function to precompute all the numbers
// till 10^5 that are palindromic and
// whose sum of digits is prime numbers
static void precompute()
{
     
    // Iterate over the range 1 to 10 ^ 5
    for(int i = 1; i <= 100000; i++)
    {
 
        // If i is a palindrome number
        if (isPalindrome(i))
        {
 
            // Stores the sum of
            // the digits in i
            int sum = sumOfDigits(i);
 
            // If the sum of digits
            // in i is a prime number
            if (isPrime(sum))
                arr[i] = 1;
            else
                arr[i] = 0;
        }
        else
            arr[i] = 0;
    }
 
    // Find the prefix sum of arr[]
    for(int i = 1; i <= 100000; i++)
    {
        arr[i] = arr[i] + arr[i - 1];
    }
}
 
// Function to count all the numbers in
// the given ranges that are palindromic
// and the sum of digits is prime numbers
static void countNumbers(int[][] Q, int N)
{
 
    // Function Call to precompute
    // all the numbers till 10^5
    precompute();
 
    // Traverse the given queries Q[]
    for(int i = 0; i < N; i++)
    {
         
        // Print the result for
        // each query
        System.out.println((arr[Q[i][1]] -
                            arr[Q[i][0] - 1]));
    }
}
 
// Driver Code
public static void main(String[] args)
{
    int[][] Q = { { 5, 9 }, { 1, 101 } };
    int N = Q.length;
 
    // Function Call
    countNumbers(Q, N);
}
}
 
// This code is contributed by user_qa7r


Python3
# Python 3 program for the above approach
arr = [0 for i in range(100005)]
 
# Function to check if the number N
# is palindrome or not
def isPalindrome(N):
   
    # Store the value of N
    temp = N
 
    # Store the reverse of number N
    res = 0
 
    # Reverse temp and store in res
    while (temp != 0):
        rem = temp % 10
        res = res * 10 + rem
        temp //= 10
 
    # If N is the same as res, then
    # return true
    if (res == N):
        return True
    else:
        return False
 
# Function to find the sum of the
# digits of the number N
def sumOfDigits(N):
   
    # Stores the sum of the digits
    sum = 0
 
    while (N != 0):
       
        # Add the last digit of the
        # number N to the sum
        sum += N % 10
 
        # Remove the last digit
        # from N
        N //= 10
 
    # Return the resultant sum
    return sum
 
# Function to check if N is prime or not
def isPrime(n):
   
    # If i is 1 or 0, then return false
    if (n <= 1):
        return False
 
    # Check if i is divisible by any
    # number in the range [2, n/2]
    for i in range(2, (n//2) + 1, 1):
       
        # If n is divisible by i
        if (n % i == 0):
            return False
 
    return True
 
# Function to precompute all the numbers
# till 10^5 that are palindromic and
# whose sum of digits is prime numbers
def precompute():
   
    # Iterate over the range 1 to 10 ^ 5
    for i in range(1, 100001, 1):
       
        # If i is a palindrome number
        if (isPalindrome(i)):
           
            # Stores the sum of
            # the digits in i
            sum = sumOfDigits(i)
 
            # If the sum of digits
            # in i is a prime number
            if (isPrime(sum)):
                arr[i] = 1
            else:
                arr[i] = 0
        else:
            arr[i] = 0
 
    # Find the prefix sum of arr[]
    for i in range(1,100001,1):
        arr[i] = arr[i] + arr[i - 1]
 
# Function to count all the numbers in
# the given ranges that are palindromic
# and the sum of digits is prime numbers
def countNumbers(Q, N):
   
    # Function Call to precompute
    # all the numbers till 10^5
    precompute()
 
    # Traverse the given queries Q[]
    for i in range(N):
       
        # Print the result for
        # each query
        print(arr[Q[i][1]] - arr[Q[i][0] - 1])
 
# Driver Code
if __name__ == '__main__':
    Q = [[5, 9], [1, 101]]
    N = len(Q)
 
    # Function Call
    countNumbers(Q, N)
 
    # This code is contributed by bgangwar59.


C#
// C# program for the above approach
using System;
 
class GFG{
 
static int[] arr = new int[100005];
 
// Function to check if the number N
// is palindrome or not
static bool isPalindrome(int N)
{
    int temp = N;
 
    // Store the reverse of number N
    int res = 0;
 
    // Reverse temp and store in res
    while (temp != 0)
    {
        int rem = temp % 10;
        res = res * 10 + rem;
        temp /= 10;
    }
 
    // If N is the same as res, then
    // return true
    if (res == N)
    {
        return true;
    }
    else
    {
        return false;
    }
}
 
// Function to find the sum of the
// digits of the number N
static int sumOfDigits(int N)
{
 
    // Stores the sum of the digits
    int sum = 0;
 
    while (N != 0)
    {
         
        // Add the last digit of the
        // number N to the sum
        sum += N % 10;
 
        // Remove the last digit
        // from N
        N /= 10;
    }
 
    // Return the resultant sum
    return sum;
}
 
// Function to check if N is prime or not
static bool isPrime(int n)
{
    // If i is 1 or 0, then return false
    if (n <= 1)
    {
        return false;
    }
 
    // Check if i is divisible by any
    // number in the range [2, n/2]
    for(int i = 2; i <= n / 2; ++i)
    {
         
        // If n is divisible by i
        if (n % i == 0)
            return false;
    }
    return true;
}
 
// Function to precompute all the numbers
// till 10^5 that are palindromic and
// whose sum of digits is prime numbers
static void precompute()
{
     
    // Iterate over the range 1 to 10 ^ 5
    for(int i = 1; i <= 100000; i++)
    {
         
        // If i is a palindrome number
        if (isPalindrome(i))
        {
             
            // Stores the sum of
            // the digits in i
            int sum = sumOfDigits(i);
 
            // If the sum of digits
            // in i is a prime number
            if (isPrime(sum))
                arr[i] = 1;
            else
                arr[i] = 0;
        }
        else
            arr[i] = 0;
    }
 
    // Find the prefix sum of arr[]
    for(int i = 1; i <= 100000; i++)
    {
        arr[i] = arr[i] + arr[i - 1];
    }
}
 
// Function to count all the numbers in
// the given ranges that are palindromic
// and the sum of digits is prime numbers
static void countNumbers(int[, ] Q, int N)
{
 
    // Function Call to precompute
    // all the numbers till 10^5
    precompute();
 
    // Traverse the given queries Q[]
    for(int i = 0; i < N; i++)
    {
         
        // Print the result for
        // each query
        Console.WriteLine((arr[Q[i, 1]] -
                           arr[Q[i, 0] - 1]));
    }
}
 
// Driver Code
static public void Main()
{
    int[,] Q = { { 5, 9 }, { 1, 101 } };
    int N = Q.GetLength(0);
   
    // Function Call
    countNumbers(Q, N);
}
}
 
// This code is contributed by Dharanendra L V.


输出:
2
6

时间复杂度: O(N * log N)
辅助空间: O(M),其中M是每个查询中的最大元素