Open In App

Largest palindromic prime in an array

Improve
Improve
Like Article
Like
Save
Share
Report

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:

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++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function that returns true if n is a palindrome
bool isPal(int n)
{
    // Find the appropriate divisor
    // to extract the leading digit
    int divisor = 1;
    while (n / divisor >= 10)
        divisor *= 10;
 
    while (n != 0) {
        int leading = n / divisor;
        int trailing = n % 10;
 
        // If first and last digit
        // not same return false
        if (leading != trailing)
            return false;
 
        // Removing the leading and trailing
        // digit from number
        n = (n % divisor) / 10;
 
        // Reducing divisor by a factor
        // of 2 as 2 digits are dropped
        divisor = divisor / 100;
    }
    return true;
}
 
// Function to return the largest
// palindromic prime present in the array
int maxPalindromicPrime(int arr[], int n)
{
    int maxElement = *max_element(arr, arr + n);
 
    // 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.
    bool prime[maxElement + 1];
    memset(prime, true, sizeof(prime));
 
    // 0 and 1 are not primes
    prime[0] = prime[1] = false;
    for (int p = 2; p * p <= maxElement; p++) {
 
        // If prime[p] is not changed, then it is
        // a prime
        if (prime[p] == true) {
 
            // Update all multiples of p
            for (int i = p * 2; i <= maxElement; i += p)
                prime[i] = false;
        }
    }
 
    int currentMax = -1;
    for (int i = 0; i < n; i++)
 
        // If arr[i] is prime as well as palindrome
        if (prime[arr[i]] && isPal(arr[i]))
            currentMax = max(currentMax, arr[i]);
 
    return currentMax;
}
 
// Driver Program
int main()
{
    int arr[] = { 11, 5, 121, 7, 89 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << maxPalindromicPrime(arr, n);
    return 0;
}


Java




// Java implementation of the above approach
 
import java.util.Arrays;
public class GFG{
  
    // Function that returns true if n is a palindrome
    static boolean isPal(int n)
    {
        // Find the appropriate divisor
        // to extract the leading digit
        int divisor = 1;
        while (n / divisor >= 10)
            divisor *= 10;
      
        while (n != 0) {
            int leading = n / divisor;
            int trailing = n % 10;
      
            // If first and last digit
            // not same return false
            if (leading != trailing)
                return false;
      
            // Removing the leading and trailing
            // digit from number
            n = (n % divisor) / 10;
      
            // Reducing divisor by a factor
            // of 2 as 2 digits are dropped
            divisor = divisor / 100;
        }
        return true;
    }
      
    // Function to return the largest
    // palindromic prime present in the array
    static int maxPalindromicPrime(int []arr, int n)
    {
        int maxElement = Arrays.stream(arr).max().getAsInt();
      
        // 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.
        boolean []prime = new boolean[maxElement + 1];
        for (int i = 0; i < maxElement + 1 ; i++)
            prime[i] = true ;
  
        // 0 and 1 are not primes
        prime[0] = prime[1] = false;
        for (int p = 2; p * p <= maxElement; p++) {
      
            // If prime[p] is not changed, then it is
            // a prime
            if (prime[p] == true) {
      
                // Update all multiples of p
                for (int i = p * 2; i <= maxElement; i += p)
                    prime[i] = false;
            }
        }
      
        int currentMax = -1;
        for (int i = 0; i < n; i++)
      
            // If arr[i] is prime as well as palindrome
            if (prime[arr[i]] == true && isPal(arr[i]) == true)
                currentMax = Math.max(currentMax, arr[i]);
      
        return currentMax;
    }
      
    // Driver Program
     public static void main(String []args)
    {
        int []arr = { 11, 5, 121, 7, 89 };
        int n = arr.length ;
        System.out.println(maxPalindromicPrime(arr, n)) ;
    }
      
}
// This code is contributed by 29AjayKumar


Python3




# Python 3 implementation of the approach
from math import sqrt
 
# Function that returns true
# if n is a palindrome
def isPal(n):
     
    # Find the appropriate divisor
    # to extract the leading digit
    divisor = 1
    while (n / divisor >= 10):
        divisor *= 10
 
    while (n != 0):
        leading = int(n / divisor)
        trailing = n % 10
 
        # If first and last digit
        # not same return false
        if (leading != trailing):
            return False
 
        # Removing the leading and trailing
        # digit from number
        n = int((n % divisor) / 10)
 
        # Reducing divisor by a factor
        # of 2 as 2 digits are dropped
        divisor = int(divisor / 100)
     
    return True
 
# Function to return the largest
# palindromic prime present in the array
def maxPalindromicPrime(arr, n):
    maxElement = arr[0]
    for i in range(len(arr)):
        if (arr[i]>maxElement):
            maxElement = arr[i]
 
    # 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.
    prime = [True for i in range(maxElement + 1)]
 
    # 0 and 1 are not primes
    prime[0] = False
    prime[1] = False
    for p in range(2, int(sqrt(maxElement)) + 1, 1):
         
        # If prime[p] is not changed,
        # then it is a prime
        if (prime[p] == True):
             
            # Update all multiples of p
            for i in range(p * 2,maxElement + 1, p):
                prime[i] = False
     
    currentMax = -1
    for i in range(n):
         
        # If arr[i] is prime as well as palindrome
        if (prime[arr[i]] and isPal(arr[i])):
            currentMax = max(currentMax, arr[i])
 
    return currentMax
 
# Driver Code
if __name__ == '__main__':
    arr = [11, 5, 121, 7, 89]
    n = len(arr)
    print(maxPalindromicPrime(arr, n))
 
# This code is contributed by
# Shashank_Shamra


C#




// C# implementation of the above approach
 
using System ;
using System.Linq ;
 
public class GFG{
 
    // Function that returns true if n is a palindrome
    static bool isPal(int n)
    {
        // Find the appropriate divisor
        // to extract the leading digit
        int divisor = 1;
        while (n / divisor >= 10)
            divisor *= 10;
     
        while (n != 0) {
            int leading = n / divisor;
            int trailing = n % 10;
     
            // If first and last digit
            // not same return false
            if (leading != trailing)
                return false;
     
            // Removing the leading and trailing
            // digit from number
            n = (n % divisor) / 10;
     
            // Reducing divisor by a factor
            // of 2 as 2 digits are dropped
            divisor = divisor / 100;
        }
        return true;
    }
     
    // Function to return the largest
    // palindromic prime present in the array
    static int maxPalindromicPrime(int []arr, int n)
    {
        int maxElement = arr.Max() ;
     
        // 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.
        bool []prime = new bool [maxElement + 1];
        for (int i = 0; i < maxElement + 1 ; i++)
            prime[i] = true ;
 
        // 0 and 1 are not primes
        prime[0] = prime[1] = false;
        for (int p = 2; p * p <= maxElement; p++) {
     
            // If prime[p] is not changed, then it is
            // a prime
            if (prime[p] == true) {
     
                // Update all multiples of p
                for (int i = p * 2; i <= maxElement; i += p)
                    prime[i] = false;
            }
        }
     
        int currentMax = -1;
        for (int i = 0; i < n; i++)
     
            // If arr[i] is prime as well as palindrome
            if (prime[arr[i]] == true && isPal(arr[i]) == true)
                currentMax = Math.Max(currentMax, arr[i]);
     
        return currentMax;
    }
     
    // Driver Program
     public static void Main()
    {
        int []arr = { 11, 5, 121, 7, 89 };
        int n = arr.Length ;
        Console.WriteLine(maxPalindromicPrime(arr, n)) ;
    }
     
    // This code is contributed by Ryuga
}


PHP




<?php
// PHP implementation of the approach
 
// Function that returns true
// if n is a palindrome
function isPal($n)
{
    // Find the appropriate divisor
    // to extract the leading digit
    $divisor = 1;
    while ((int)($n / $divisor) >= 10)
        $divisor *= 10;
 
    while ($n != 0)
    {
        $leading = (int)($n / $divisor);
        $trailing = $n % 10;
 
        // If first and last digit
        // not same return false
        if ($leading != $trailing)
            return false;
 
        // Removing the leading and trailing
        // digit from number
        $n = (int)(($n % $divisor) / 10);
 
        // Reducing divisor by a factor
        // of 2 as 2 digits are dropped
        $divisor = (int)($divisor / 100);
    }
    return true;
}
 
// Function to return the largest
// palindromic prime present in the array
function maxPalindromicPrime($arr, $n)
{
    $maxElement = max($arr);
 
    // 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.
    $prime = array_fill(0, ($maxElement + 1), true);
 
    // 0 and 1 are not primes
    $prime[0] = $prime[1] = false;
    for ($p = 2; $p * $p <= $maxElement; $p++)
    {
 
        // If prime[p] is not changed,
        // then it is a prime
        if ($prime[$p] == true)
        {
 
            // Update all multiples of p
            for ($i = $p * 2;
                 $i <= $maxElement; $i += $p)
                $prime[$i] = false;
        }
    }
 
    $currentMax = -1;
    for ($i = 0; $i < $n; $i++)
 
        // If arr[i] is prime as well as palindrome
        if ($prime[$arr[$i]] && isPal($arr[$i]))
            $currentMax = max($currentMax, $arr[$i]);
 
    return $currentMax;
}
 
// Driver Code
$arr = array( 11, 5, 121, 7, 89 );
$n = count($arr);
echo maxPalindromicPrime($arr, $n);
 
// This code is contributed by mits
?>


Javascript




<script>
// Javascript implementation of the approach
 
// Function that returns true
// if n is a palindrome
function isPal(n) {
    // Find the appropriate divisor
    // to extract the leading digit
    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 first and last digit
        // not same return false
        if (leading != trailing)
            return false;
 
        // Removing the leading and trailing
        // digit from number
        n = Math.floor((n % divisor) / 10);
 
        // Reducing divisor by a factor
        // of 2 as 2 digits are dropped
        divisor = Math.floor(divisor / 100);
    }
    return true;
}
 
// Function to return the largest
// palindromic prime present in the array
function maxPalindromicPrime(arr, n) {
    let maxElement = arr.sort((a, b) => a - b).reverse()[0];
 
    // 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.
    let prime = new Array(maxElement + 1).fill(true);
 
    // 0 and 1 are not primes
    prime[0] = prime[1] = false;
    for (let p = 2; p * p <= maxElement; p++) {
 
        // If prime[p] is not changed,
        // then it is a prime
        if (prime[p] == true) {
 
            // Update all multiples of p
            for (let i = p * 2;
                i <= maxElement; i += p)
                prime[i] = false;
        }
    }
 
    let currentMax = -1;
    for (let i = 0; i < n; i++)
 
        // If arr[i] is prime as well as palindrome
        if (prime[arr[i]] && isPal(arr[i]))
            currentMax = Math.max(currentMax, arr[i]);
 
    return currentMax;
}
 
// Driver Code
let arr = [11, 5, 121, 7, 89];
let n = arr.length;
document.write(maxPalindromicPrime(arr, n));
 
// This code is contributed by gfgking
</script>


Output

11

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




# Python3 Program to implement
# the above approach
 
# function to check if a number is prime
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
 
# function to check if a number is palindrome
def is_palindrome(n):
    reversed = 0
    original = n
    while n > 0:
        reversed = reversed * 10 + n % 10
        n //= 10
     
    return reversed == original
 
# Driver code
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#




// A C# program to find the largest palindromic prime in an
// array
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 + ".");
        }
    }
}
// This code is contributed by sarojmcy2e


Javascript




// JavaScript code
 
// function to check if a number is prime
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 to check if a number is palindrome
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;
}
 
// Driver code
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.



Last Updated : 31 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads