Palindromic Primes | C ++ Program to print all palindromic primes smaller than or equal to n . ; A function that returns true only if num contains one digit ; comparison operation is faster than division operation . So using following instead of " return ▁ num ▁ / ▁ 10 ▁ = = ▁ 0 ; " ; A recursive function to find out whether num is palindrome or not . Initially , dupNum contains address of a copy of num . ; Base case ( needed for recursion termination ) : This statement / mainly compares the first digit with the last digit ; This is the key line in this method . Note that all recursive / calls have a separate copy of num , but they all share same copy of * dupNum . We divide num while moving up the recursion tree ; The following statements are executed when we move up the recursion call tree ; At this point , if num % 10 contains i ' th ▁ ▁ digit ▁ from ▁ beginning , ▁ then ▁ ( * dupNum ) %10 ▁ ▁ contains ▁ i ' th digit from end ; The main function that uses recursive function isPalUtil ( ) to find out whether num is palindrome or not ; If num is negative , make it positive ; Create a separate copy of num , so that modifications made to address dupNum don 't  change the input number.  int *dupNum = new int(num); *dupNum = num ; Function to generate all primes and checking whether number is palindromic or not ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Print all palindromic prime numbers ; checking whether the given number is prime palindromic or not ; Driver Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int oneDigit ( int num ) { return ( num >= 0 && num < 10 ) ; } bool isPalUtil ( int num , int * dupNum ) { if ( oneDigit ( num ) ) return ( num == ( * dupNum ) % 10 ) ; if ( ! isPalUtil ( num / 10 , dupNum ) ) return false ; * dupNum /= 10 ; return ( num % 10 == ( * dupNum ) % 10 ) ; } int isPal ( int num ) { if ( num < 0 ) num = - num ; return isPalUtil ( num , dupNum ) ; } void printPalPrimesLessThanN ( int n ) { bool prime [ n + 1 ] ; memset ( prime , true , sizeof ( prime ) ) ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i <= n ; i += p ) prime [ i ] = false ; } } for ( int p = 2 ; p <= n ; p ++ ) if ( prime [ p ] && isPal ( p ) ) cout << p << " ▁ " ; } int main ( ) { int n = 100 ; printf ( " Palindromic ▁ primes ▁ smaller ▁ than ▁ or ▁ " " equal ▁ to ▁ % d ▁ are ▁ : STRNEWLINE " , n ) ; printPalPrimesLessThanN ( n ) ; }