Open In App

Find prime number K in an array such that (A[i] % K) is maximum

Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of n integers. The task is to find an element from the array K such that 
 

  1. K is prime.
  2. And, arr[i] % K is the maximum for all valid i among all possible values of K

if there is no prime number in the array then print -1.
Examples: 
 

Input: arr[] = {2, 10, 15, 7, 6, 8, 13} 
Output: 13 
2, 7 and 13 are the only prime numbers in the array. 
The maximum possible value of arr[i] % 2 is 1 i.e. 15 % 2 = 1. 
For 7, it is 6 % 7 = 6 
For 13, 10 % 13 = 10 (Maximum possible)
Input: arr[] = {23, 13, 6, 2, 15, 18, 8} 
Output: 23 
 

 

Approach: In order to maximize the value of arr[i] % K, K must be the maximum prime number from the array and arr[i] must be the greatest element from the array which is less than K. So, the problem now gets reduced to finding the maximum prime number from the array. In order to do that, 
 

  1. First, find all the prime numbers less than or equal to the maximum element from the array using Sieve.
  2. Then, find the maximum prime number from the array and print it. If there is no prime present in the array then print -1.

Below is the implementation of the above approach: 
 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the required
// prime number from the array
int getPrime(int arr[], int n)
{
    // Find maximum value in the array
    int max_val = *max_element(arr, arr + n);
 
    // USE SIEVE TO FIND ALL PRIME NUMBERS LESS
    // THAN OR EQUAL TO max_val
    // Create a boolean array "prime[0..n]". A
    // value in prime[i] will finally be false
    // if i is Not a prime, else true.
    vector<bool> prime(max_val + 1, true);
 
    // Remaining part of SIEVE
    prime[0] = false;
    prime[1] = false;
    for (int p = 2; p * p <= max_val; 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 <= max_val; i += p)
                prime[i] = false;
        }
    }
 
    // To store the maximum prime number
    int maximum = -1;
    for (int i = 0; i < n; i++) {
 
        // If current element is prime
        // then update the maximum prime
        if (prime[arr[i]])
            maximum = max(maximum, arr[i]);
    }
 
    // Return the maximum prime
    // number from the array
    return maximum;
}
 
// Driver code
int main()
{
    int arr[] = { 2, 10, 15, 7, 6, 8, 13 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    cout << getPrime(arr, n);
 
    return 0;
}


Java




// Java implementation of the approach
import java.util.*;
 
class GFG
{
 
// Function to return the required
// prime number from the array
static int getPrime(int arr[], int n)
{
    // Find maximum value in the array
    int max_val = Arrays.stream(arr).max().getAsInt();
 
    // USE SIEVE TO FIND ALL PRIME NUMBERS LESS
    // THAN OR EQUAL TO max_val
    // Create a boolean array "prime[0..n]". A
    // value in prime[i] will finally be false
    // if i is Not a prime, else true.
    Vector<Boolean> prime = new Vector<>(max_val + 1);
    for(int i = 0; i < max_val + 1; i++)
        prime.add(i,Boolean.TRUE);
 
    // Remaining part of SIEVE
    prime.add(1,Boolean.FALSE);
    prime.add(2,Boolean.FALSE);
    for (int p = 2; p * p <= max_val; p++)
    {
 
        // If prime[p] is not changed, then
        // it is a prime
        if (prime.get(p) == true)
        {
 
            // Update all multiples of p
            for (int i = p * 2; i <= max_val; i += p)
                prime.add(i,Boolean.FALSE);
        }
    }
 
    // To store the maximum prime number
    int maximum = -1;
    for (int i = 0; i < n; i++)
    {
 
        // If current element is prime
        // then update the maximum prime
        if (prime.get(arr[i]))
        {
            maximum = Math.max(maximum, arr[i]);
        }
             
    }
 
    // Return the maximum prime
    // number from the array
    return maximum;
}
 
// Driver code
public static void main(String[] args)
{
    int arr[] = { 2, 10, 15, 7, 6, 8, 13 };
    int n = arr.length;
 
    System.out.println(getPrime(arr, n));
}
}
 
// This code has been contributed by 29AjayKumar


Python3




# Python 3 implementation of the approach
from math import sqrt
 
# Function to return the required
# prime number from the array
def getPrime(arr, n):
     
    # Find maximum value in the array
    max_val = arr[0]
    for i in range(len(arr)):
         
        # USE SIEVE TO FIND ALL PRIME NUMBERS LESS
        # THAN OR EQUAL TO max_val
        # Create a boolean array "prime[0..n]". A
        # value in prime[i] will finally be false
        # if i is Not a prime, else true.
        if(arr[i] > max_val):
            max_val = arr[i]
 
    prime = [True for i in range(max_val + 1)]
  
    # Remaining part of SIEVE
    prime[0] = False
    prime[1] = False
    for p in range(2, int(sqrt(max_val)) + 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, max_val + 1, p):
                prime[i] = False
 
    # To store the maximum prime number
    maximum = -1
    for i in range(n):
         
        # If current element is prime
        # then update the maximum prime
        if (prime[arr[i]]):
            maximum = max(maximum, arr[i])
 
    # Return the maximum prime
    # number from the array
    return maximum
 
# Driver code
if __name__ == '__main__':
    arr = [2, 10, 15, 7, 6, 8, 13]
    n = len(arr)
 
    print(getPrime(arr, n))
     
# This code is contributed by
# Surendra_Gangwar


C#




// C# implementation of the approach
using System;
using System.Linq;
using System.Collections.Generic;
     
class GFG
{
 
// Function to return the required
// prime number from the array
static int getPrime(int []arr, int n)
{
    // Find maximum value in the array
    int max_val = arr.Max();
 
    // USE SIEVE TO FIND ALL PRIME NUMBERS LESS
    // THAN OR EQUAL TO max_val
    // Create a boolean array "prime[0..n]". A
    // value in prime[i] will finally be false
    // if i is Not a prime, else true.
    List<Boolean> prime = new List<Boolean>(max_val + 1);
    for(int i = 0; i < max_val + 1; i++)
        prime.Insert(i, true);
 
    // Remaining part of SIEVE
    prime.Insert(1, false);
    prime.Insert(2, false);
    for (int p = 2; p * p <= max_val; 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 <= max_val; i += p)
                prime.Insert(i, false);
        }
    }
 
    // To store the maximum prime number
    int maximum = -1;
    for (int i = 0; i < n; i++)
    {
 
        // If current element is prime
        // then update the maximum prime
        if (prime[arr[i]])
        {
            maximum = Math.Max(maximum, arr[i]);
        }
             
    }
 
    // Return the maximum prime
    // number from the array
    return maximum;
}
 
// Driver code
public static void Main(String[] args)
{
    int []arr = { 2, 10, 15, 7, 6, 8, 13 };
    int n = arr.Length;
 
    Console.WriteLine(getPrime(arr, n));
}
}
 
// This code contributed by Rajput-Ji


PHP




<?php
// PHP implementation of the approach
 
// Function to return the count of primes
// in the given array
function getPrime($arr, $n)
{
    // Find maximum value in the array
    $max_val = max($arr);
 
    // USE SIEVE TO FIND ALL PRIME NUMBERS LESS
    // THAN OR EQUAL TO max_val
    // Create a boolean array "prime[0..n]". A
    // value in prime[i] will finally be false
    // if i is Not a prime, else true.
    $prime = array_fill(0, $max_val + 1, true);
 
    // Remaining part of SIEVE
    $prime[0] = false;
    $prime[1] = false;
    for ($p = 2; $p * $p <= $max_val; $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 <= $max_val; $i += $p)
                $prime[$i] = false;
        }
    }
 
    // To store the maximum prime number
    $maximum = -1;
     
    for ($i = 0; $i < $n; $i++)
    {
 
        // If current element is prime
        // then update the maximum prime
        if ($prime[$arr[$i]])
            $maximum = max($maximum, $arr[$i]);
    }
 
    // Return the maximum prime
    // number from the array
    return $maximum;
}
 
// Driver code
$arr = array( 2, 10, 15, 7, 6, 8, 13 );
$n = count($arr) ;
 
echo getPrime($arr, $n);
 
// This code is contributed by AnkitRai01
?>


Javascript




<script>
 
// Javascript implementation of the approach
 
// Function to return the required
// prime number from the array
function getPrime(arr, n)
{
    // Find maximum value in the array
    let max_val = Math.max(...arr);
 
    // USE SIEVE TO FIND ALL PRIME NUMBERS LESS
    // THAN OR EQUAL TO max_val
    // Create a boolean array "prime[0..n]". A
    // value in prime[i] will finally be false
    // if i is Not a prime, else true.
    let prime = new Array(max_val + 1).fill(true);
 
    // Remaining part of SIEVE
    prime[0] = false;
    prime[1] = false;
    for (let p = 2; p * p <= max_val; 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 <= max_val; i += p)
                prime[i] = false;
        }
    }
 
    // To store the maximum prime number
    let maximum = -1;
    for (let i = 0; i < n; i++) {
 
        // If current element is prime
        // then update the maximum prime
        if (prime[arr[i]])
            maximum = Math.max(maximum, arr[i]);
    }
 
    // Return the maximum prime
    // number from the array
    return maximum;
}
 
// Driver code
    let arr = [ 2, 10, 15, 7, 6, 8, 13 ];
    let n = arr.length;
 
    document.write(getPrime(arr, n));
 
</script>


Output: 

13

 

Time Complexity: O(n + max), where max is the largest element of the array.

Auxiliary Space: O(max), where max is the maximum element of the array.



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