Largest palindromic prime in an array
Last Updated :
31 Mar, 2023
Given an array arr[] of integers, the task is to print the largest palindromic prime from the array. If no element from the array is a palindromic prime then print -1.
Examples:
Input: arr[] = {11, 5, 121, 7, 89}
Output: 11
11, 5 and 7 are the only primes from the array which are palindromes.
11 is the maximum among them.
Input: arr[] = {2, 4, 6, 8, 10}
Output: 2
A simple approach is to go through every array element, check if it is prime and check if it is palindrome. If yes, the update the result if it is greater than current result also.
Efficient approach for large number of elements:
- Use Sieve of Eratosthenes to calculate whether a number is prime or not upto the maximum element from the array.
- Now, initialize a variable currentMax = -1 and start traversing the array arr[].
- For every i, if arr[i] is prime as well as palindrome and arr[i] > currentMax then update currentMax = arr[i].
- Print currentMax in the end.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool isPal( int n)
{
int divisor = 1;
while (n / divisor >= 10)
divisor *= 10;
while (n != 0) {
int leading = n / divisor;
int trailing = n % 10;
if (leading != trailing)
return false ;
n = (n % divisor) / 10;
divisor = divisor / 100;
}
return true ;
}
int maxPalindromicPrime( int arr[], int n)
{
int maxElement = *max_element(arr, arr + n);
bool prime[maxElement + 1];
memset (prime, true , sizeof (prime));
prime[0] = prime[1] = false ;
for ( int p = 2; p * p <= maxElement; p++) {
if (prime[p] == true ) {
for ( int i = p * 2; i <= maxElement; i += p)
prime[i] = false ;
}
}
int currentMax = -1;
for ( int i = 0; i < n; i++)
if (prime[arr[i]] && isPal(arr[i]))
currentMax = max(currentMax, arr[i]);
return currentMax;
}
int main()
{
int arr[] = { 11, 5, 121, 7, 89 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << maxPalindromicPrime(arr, n);
return 0;
}
|
Java
import java.util.Arrays;
public class GFG{
static boolean isPal( int n)
{
int divisor = 1 ;
while (n / divisor >= 10 )
divisor *= 10 ;
while (n != 0 ) {
int leading = n / divisor;
int trailing = n % 10 ;
if (leading != trailing)
return false ;
n = (n % divisor) / 10 ;
divisor = divisor / 100 ;
}
return true ;
}
static int maxPalindromicPrime( int []arr, int n)
{
int maxElement = Arrays.stream(arr).max().getAsInt();
boolean []prime = new boolean [maxElement + 1 ];
for ( int i = 0 ; i < maxElement + 1 ; i++)
prime[i] = true ;
prime[ 0 ] = prime[ 1 ] = false ;
for ( int p = 2 ; p * p <= maxElement; p++) {
if (prime[p] == true ) {
for ( int i = p * 2 ; i <= maxElement; i += p)
prime[i] = false ;
}
}
int currentMax = - 1 ;
for ( int i = 0 ; i < n; i++)
if (prime[arr[i]] == true && isPal(arr[i]) == true )
currentMax = Math.max(currentMax, arr[i]);
return currentMax;
}
public static void main(String []args)
{
int []arr = { 11 , 5 , 121 , 7 , 89 };
int n = arr.length ;
System.out.println(maxPalindromicPrime(arr, n)) ;
}
}
|
Python3
from math import sqrt
def isPal(n):
divisor = 1
while (n / divisor > = 10 ):
divisor * = 10
while (n ! = 0 ):
leading = int (n / divisor)
trailing = n % 10
if (leading ! = trailing):
return False
n = int ((n % divisor) / 10 )
divisor = int (divisor / 100 )
return True
def maxPalindromicPrime(arr, n):
maxElement = arr[ 0 ]
for i in range ( len (arr)):
if (arr[i]>maxElement):
maxElement = arr[i]
prime = [ True for i in range (maxElement + 1 )]
prime[ 0 ] = False
prime[ 1 ] = False
for p in range ( 2 , int (sqrt(maxElement)) + 1 , 1 ):
if (prime[p] = = True ):
for i in range (p * 2 ,maxElement + 1 , p):
prime[i] = False
currentMax = - 1
for i in range (n):
if (prime[arr[i]] and isPal(arr[i])):
currentMax = max (currentMax, arr[i])
return currentMax
if __name__ = = '__main__' :
arr = [ 11 , 5 , 121 , 7 , 89 ]
n = len (arr)
print (maxPalindromicPrime(arr, n))
|
C#
using System ;
using System.Linq ;
public class GFG{
static bool isPal( int n)
{
int divisor = 1;
while (n / divisor >= 10)
divisor *= 10;
while (n != 0) {
int leading = n / divisor;
int trailing = n % 10;
if (leading != trailing)
return false ;
n = (n % divisor) / 10;
divisor = divisor / 100;
}
return true ;
}
static int maxPalindromicPrime( int []arr, int n)
{
int maxElement = arr.Max() ;
bool []prime = new bool [maxElement + 1];
for ( int i = 0; i < maxElement + 1 ; i++)
prime[i] = true ;
prime[0] = prime[1] = false ;
for ( int p = 2; p * p <= maxElement; p++) {
if (prime[p] == true ) {
for ( int i = p * 2; i <= maxElement; i += p)
prime[i] = false ;
}
}
int currentMax = -1;
for ( int i = 0; i < n; i++)
if (prime[arr[i]] == true && isPal(arr[i]) == true )
currentMax = Math.Max(currentMax, arr[i]);
return currentMax;
}
public static void Main()
{
int []arr = { 11, 5, 121, 7, 89 };
int n = arr.Length ;
Console.WriteLine(maxPalindromicPrime(arr, n)) ;
}
}
|
PHP
<?php
function isPal( $n )
{
$divisor = 1;
while ((int)( $n / $divisor ) >= 10)
$divisor *= 10;
while ( $n != 0)
{
$leading = (int)( $n / $divisor );
$trailing = $n % 10;
if ( $leading != $trailing )
return false;
$n = (int)(( $n % $divisor ) / 10);
$divisor = (int)( $divisor / 100);
}
return true;
}
function maxPalindromicPrime( $arr , $n )
{
$maxElement = max( $arr );
$prime = array_fill (0, ( $maxElement + 1), true);
$prime [0] = $prime [1] = false;
for ( $p = 2; $p * $p <= $maxElement ; $p ++)
{
if ( $prime [ $p ] == true)
{
for ( $i = $p * 2;
$i <= $maxElement ; $i += $p )
$prime [ $i ] = false;
}
}
$currentMax = -1;
for ( $i = 0; $i < $n ; $i ++)
if ( $prime [ $arr [ $i ]] && isPal( $arr [ $i ]))
$currentMax = max( $currentMax , $arr [ $i ]);
return $currentMax ;
}
$arr = array ( 11, 5, 121, 7, 89 );
$n = count ( $arr );
echo maxPalindromicPrime( $arr , $n );
?>
|
Javascript
<script>
function isPal(n) {
let divisor = 1;
while (Math.floor(n / divisor) >= 10)
divisor *= 10;
while (n != 0) {
let leading = Math.floor(n / divisor);
let trailing = n % 10;
if (leading != trailing)
return false ;
n = Math.floor((n % divisor) / 10);
divisor = Math.floor(divisor / 100);
}
return true ;
}
function maxPalindromicPrime(arr, n) {
let maxElement = arr.sort((a, b) => a - b).reverse()[0];
let prime = new Array(maxElement + 1).fill( true );
prime[0] = prime[1] = false ;
for (let p = 2; p * p <= maxElement; p++) {
if (prime[p] == true ) {
for (let i = p * 2;
i <= maxElement; i += p)
prime[i] = false ;
}
}
let currentMax = -1;
for (let i = 0; i < n; i++)
if (prime[arr[i]] && isPal(arr[i]))
currentMax = Math.max(currentMax, arr[i]);
return currentMax;
}
let arr = [11, 5, 121, 7, 89];
let n = arr.length;
document.write(maxPalindromicPrime(arr, n));
</script>
|
Another Approach:
Define two helper functions: is_prime() and is_palindrome(). The is_prime() function checks if a given number is prime or not using a basic primality test, and returns a boolean value. The is_palindrome() function checks if a given number is a palindrome or not, and returns a boolean value.
Define an array of integers arr containing some values for the purpose of example. Calculate the size of the array using sizeof() and arr[0], and store it in the variable size.
Initialize the variable largest_pal_prime to -1. This is the default value to be used in case there are no palindromic primes found in the array.
Use a for loop to iterate over each element in the array. For each element, check if it is a palindrome and a prime using the helper functions. If it is both a palindrome and a prime, and its value is greater than the current largest_pal_prime, set largest_pal_prime to the value of the current element.
After the loop has been completed, check if largest_pal_prime is still equal to -1. If it is, print a message indicating that no palindromic primes were found in the array. Otherwise, print the value of largest_pal_prime.
C++
#include <bits/stdc++.h>
using namespace std;
bool is_prime( int n) {
if (n < 2) {
return false ;
}
for ( int i = 2; i * i <= n; i++) {
if (n % i == 0) {
return false ;
}
}
return true ;
}
bool is_palindrome( int n) {
int reversed = 0;
int original = n;
while (n > 0) {
reversed = reversed * 10 + n % 10;
n /= 10;
}
return (reversed == original);
}
int main() {
vector< int > arr = {13, 101, 37, 313, 79, 181, 97, 131, 23, 199};
int size = arr.size();
int largest_pal_prime = -1;
for ( int i = 0; i < size; i++) {
int current_num = arr[i];
if (is_prime(current_num) && is_palindrome(current_num)) {
if (current_num > largest_pal_prime) {
largest_pal_prime = current_num;
}
}
}
if (largest_pal_prime == -1) {
cout << "No palindromic prime found in the array." <<endl;
} else {
cout << "The largest palindromic prime in the array is " << largest_pal_prime << "." <<endl;
}
return 0;
}
|
C
#include <stdio.h>
#include <stdbool.h>
bool is_prime( int n) {
if (n < 2) {
return false ;
}
for ( int i = 2; i * i <= n; i++) {
if (n % i == 0) {
return false ;
}
}
return true ;
}
bool is_palindrome( int n) {
int reversed = 0;
int original = n;
while (n > 0) {
reversed = reversed * 10 + n % 10;
n /= 10;
}
return (reversed == original);
}
int main() {
int arr[] = {13, 101, 37, 313, 79, 181, 97, 131, 23, 199};
int size = sizeof (arr) / sizeof (arr[0]);
int largest_pal_prime = -1;
for ( int i = 0; i < size; i++) {
int current_num = arr[i];
if (is_prime(current_num) && is_palindrome(current_num)) {
if (current_num > largest_pal_prime) {
largest_pal_prime = current_num;
}
}
}
if (largest_pal_prime == -1) {
printf ( "No palindromic prime found in the array.\n" );
} else {
printf ( "The largest palindromic prime in the array is %d.\n" , largest_pal_prime);
}
return 0;
}
|
Java
import java.util.*;
public class Main {
public static boolean is_prime( int n) {
if (n < 2 ) {
return false ;
}
for ( int i = 2 ; i * i <= n; i++) {
if (n % i == 0 ) {
return false ;
}
}
return true ;
}
public static boolean is_palindrome( int n) {
int reversed = 0 ;
int original = n;
while (n > 0 ) {
reversed = reversed * 10 + n % 10 ;
n /= 10 ;
}
return (reversed == original);
}
public static void main(String[] args) {
List<Integer> arr = Arrays.asList( 13 , 101 , 37 , 313 , 79 , 181 , 97 , 131 , 23 , 199 );
int size = arr.size();
int largest_pal_prime = - 1 ;
for ( int i = 0 ; i < size; i++) {
int current_num = arr.get(i);
if (is_prime(current_num) && is_palindrome(current_num)) {
if (current_num > largest_pal_prime) {
largest_pal_prime = current_num;
}
}
}
if (largest_pal_prime == - 1 ) {
System.out.println( "No palindromic prime found in the array." );
} else {
System.out.println( "The largest palindromic prime in the array is " + largest_pal_prime + "." );
}
}
}
|
Python3
def is_prime(n):
if n < 2 :
return False
for i in range ( 2 , int (n * * 0.5 ) + 1 ):
if n % i = = 0 :
return False
return True
def is_palindrome(n):
reversed = 0
original = n
while n > 0 :
reversed = reversed * 10 + n % 10
n / / = 10
return reversed = = original
arr = [ 13 , 101 , 37 , 313 , 79 , 181 , 97 , 131 , 23 , 199 ]
size = len (arr)
largest_pal_prime = - 1
for i in range (size):
current_num = arr[i]
if is_prime(current_num) and is_palindrome(current_num):
if current_num > largest_pal_prime:
largest_pal_prime = current_num
if largest_pal_prime = = - 1 :
print ( "No palindromic prime found in the array." )
else :
print ( "The largest palindromic prime in the array is {}." . format (largest_pal_prime))
|
C#
using System;
using System.Collections.Generic;
public class PalindromePrimeFinder {
static bool IsPrime( int n)
{
if (n < 2) {
return false ;
}
for ( int i = 2; i * i <= n; i++) {
if (n % i == 0) {
return false ;
}
}
return true ;
}
static bool IsPalindrome( int n)
{
int reversed = 0;
int original = n;
while (n > 0) {
reversed = reversed * 10 + n % 10;
n /= 10;
}
return (reversed == original);
}
static void Main()
{
List< int > arr
= new List< int >{ 13, 101, 37, 313, 79,
181, 97, 131, 23, 199 };
int size = arr.Count;
int largest_pal_prime = -1;
for ( int i = 0; i < size; i++) {
int current_num = arr[i];
if (IsPrime(current_num)
&& IsPalindrome(current_num)) {
if (current_num > largest_pal_prime) {
largest_pal_prime = current_num;
}
}
}
if (largest_pal_prime == -1) {
Console.WriteLine(
"No palindromic prime found in the array." );
}
else {
Console.WriteLine(
"The largest palindromic prime in the array is "
+ largest_pal_prime + "." );
}
}
}
|
Javascript
function is_prime(n) {
if (n < 2) {
return false ;
}
for (let i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false ;
}
}
return true ;
}
function is_palindrome(n) {
let reversed = 0;
let original = n;
while (n > 0) {
reversed = reversed * 10 + n % 10;
n = Math.floor(n/10);
}
return reversed == original;
}
let arr = [13, 101, 37, 313, 79, 181, 97, 131, 23, 199];
let size = arr.length;
let largest_pal_prime = -1;
for (let i = 0; i < size; i++) {
let current_num = arr[i];
if (is_prime(current_num) && is_palindrome(current_num)) {
if (current_num > largest_pal_prime) {
largest_pal_prime = current_num;
}
}
}
if (largest_pal_prime == -1) {
console.log( "No palindromic prime found in the array." );
}
else {
console.log(`The largest palindromic prime in the array is ${largest_pal_prime}.`);
}
|
Output
The largest palindromic prime in the array is 313.
The time complexity of this program is O(n*sqrt(n)), where n is the size of the array. This is because the is_prime() function performs a loop from 2 to the square root of the input number, and this loop is executed for each element in the array.
The space complexity is O(1), as the program only uses a fixed amount of memory to store the variables and the array.
Similar Reads
Largest palindromic number in an array
Given an array of non-negative integers arr[]. The task is to find the largest number in the array which is palindrome. If no such number exits then print -1. Examples: Input: arr[] = {1, 232, 54545, 999991}; Output: 54545 Input: arr[] = {1, 2, 3, 4, 5, 50}; Output: 5 Recommended: Please try your ap
15+ min read
Number of prime pairs in an array
Given an array. The task is to count the possible pairs which can be formed using the elements of the array where both of the elements in the pair are prime. Note: Pairs such as (a, b) and (b, a) should not be considered different. Examples: Input: arr[] = {1, 2, 3, 5, 7, 9} Output: 6 From the given
9 min read
Find largest prime factor of a number
Given a positive integer n ( 1 <= n <= 1015). Find the largest prime factor of a number. Input: 6Output: 3Explanation Prime factor are 2 and 3. Largest of them is 3.Input: 15Output: 5Explanation: Prime factors are 3 and 5. The largest of them is 5. Input: 28Output: 7Explanation: Prime factors
10 min read
Find next palindrome prime
Find the smallest palindrome number which is prime too and greater than given number N.Examples: Input : N = 7 Output :11 11 is the smallest palindrome prime which is greater than N. Input : N = 112 Output : 131 A simple approach is to start a loop from N+1. For every number, check if it is palindro
6 min read
Largest perfect square number in an Array
Given an array of n integers. The task is to find the largest number which is a perfect square. Print -1 if there is no number that is perfect square.Examples: Input : arr[] = {16, 20, 25, 2, 3, 10} Output : 25 Explanation: 25 is the largest number that is a perfect square. Input : arr[] = {36, 64,
8 min read
Number of co-prime pairs in an array
Co-prime or mutually prime pair are those pair of numbers whose GCD is 1. Given an array of size n, find number of Co-Prime or mutually prime pairs in the array. Examples: Input : 1 2 3 Output : 3 Here, Co-prime pairs are ( 1, 2), ( 2, 3), ( 1, 3) Input :4 8 3 9 Output :4 Here, Co-prime pairs are (
6 min read
Largest palindromic number by permuting digits
Given a very large integer n in the form of string, the task is to return the largest palindromic number obtainable by permuting the digits of n. If it is not possible to make a palindromic number, then return an empty string. Examples : Input : "313551"Output : "531135"Explanations : 531135 is the
10 min read
Find a pair in Array with second largest product
Given an array arr[] of N integers, where N > 2, the task is to find the second largest product pair from the given array. Examples: Input: arr[] = {10, 20, 12, 40, 50}Output: 20 50Explanation:A pair of array elements = [(10, 20), (10, 12), (10, 40), (10, 50), (20, 12), (20, 40), (20, 50), (12, 4
15+ min read
Count twin prime pairs in an Array
Given an array arr[] of N natural numbers. The task is to count all possible pairs in the arr[] that are Twin Primes.A Twin prime are those numbers that are prime and have a difference of two ( 2 ) between the two prime numbers. In other words, a twin prime is a prime that has a prime gap of two. Ex
8 min read
Program to find largest element in an Array
Given an array arr. The task is to find the largest element in the given array. Examples: Input: arr[] = [10, 20, 4]Output: 20Explanation: Among 10, 20 and 4, 20 is the largest. Input: arr[] = [20, 10, 20, 4, 100]Output: 100 Table of Content Iterative Approach - O(n) Time and O(1) SpaceRecursive App
7 min read