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