Given an array arr[] of N positive integers. The task is to find the minimum and maximum prime elements in the given array.
Examples:
Input: arr[] = 1, 3, 4, 5, 7
Output: Minimum : 3
Maximum : 7
Input: arr[] = 1, 2, 3, 4, 5, 6, 7, 11
Output: Minimum : 2
Maximum : 11
Naive Approach:
Take a variable min and max. Initialize min with INT_MAX and max with INT_MIN. Traverse the array and keep checking for every element if it is prime or not and update the minimum and maximum prime element at the same time.
Efficient Approach:
Generate all primes upto maximum element of the array using a sieve of Eratosthenes and store them in a hash. Now traverse the array and find the minimum and maximum elements which are prime using the hash table.
Below is the implementation of above approach:
// CPP program to find minimum and maximum // prime number in given array. #include <bits/stdc++.h> using namespace std;
// Function to find count of prime void prime( 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 ;
}
}
// Minimum and Maximum prime number
int minimum = INT_MAX;
int maximum = INT_MIN;
for ( int i = 0; i < n; i++)
if (prime[arr[i]]) {
minimum = min(minimum, arr[i]);
maximum = max(maximum, arr[i]);
}
cout << "Minimum : " << minimum << endl;
cout << "Maximum : " << maximum << endl;
} // Driver code int main()
{ int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
int n = sizeof (arr) / sizeof (arr[0]);
prime(arr, n);
return 0;
} |
// Java program to find minimum and maximum // prime number in given array. import java.util.*;
class GFG {
// Function to find count of prime static void prime( 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<Boolean>();
for ( int i= 0 ;i<max_val+ 1 ;i++)
prime.add(Boolean.TRUE);
// Remaining part of SIEVE
prime.add( 0 , Boolean.FALSE);
prime.add( 1 , 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);
}
}
// Minimum and Maximum prime number
int minimum = Integer.MAX_VALUE;
int maximum = Integer.MIN_VALUE;
for ( int i = 0 ; i < n; i++)
if (prime.get(arr[i])) {
minimum = Math.min(minimum, arr[i]);
maximum = Math.max(maximum, arr[i]);
}
System.out.println( "Minimum : " + minimum) ;
System.out.println( "Maximum : " + maximum );
} // Driver code public static void main(String[] args) {
int arr[] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 };
int n = arr.length;
prime(arr, n);
}
} /*This code is contributed by 29AjayKumar*/ |
# Python3 program to find minimum and # maximum prime number in given array. import math as mt
# Function to find count of prime def Prime(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 = [ True for i in range (max_val + 1 )]
# Remaining part of SIEVE
prime[ 0 ] = False
prime[ 1 ] = False
for p in range ( 2 , mt.ceil(mt.sqrt(max_val))):
# If prime[p] is not changed,
# then it is a prime
if (prime[p] = = True ):
# Update all multiples of p
for i in range ( 2 * p, max_val + 1 , p):
prime[i] = False
# Minimum and Maximum prime number
minimum = 10 * * 9
maximum = - 10 * * 9
for i in range (n):
if (prime[arr[i]] = = True ):
minimum = min (minimum, arr[i])
maximum = max (maximum, arr[i])
print ( "Minimum : " , minimum )
print ( "Maximum : " , maximum )
# Driver code arr = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ]
n = len (arr)
Prime(arr, n) # This code is contributed by # Mohit kumar 29 |
// A C# program to find minimum and maximum // prime number in given array. using System;
using System.Linq;
using System.Collections.Generic;
class GFG
{ // Function to find count of prime static void prime( 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< bool >prime = new List< bool >();
for ( int i = 0; i < max_val + 1;i++)
prime.Add( true );
// Remaining part of SIEVE
prime.Insert(0, false );
prime.Insert(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.Insert(i, false );
}
}
// Minimum and Maximum prime number
int minimum = int .MaxValue;
int maximum = int .MinValue;
for ( int i = 0; i < n; i++)
if (prime[arr[i]])
{
minimum = Math.Min(minimum, arr[i]);
maximum = Math.Max(maximum, arr[i]);
}
Console.WriteLine( "Minimum : " + minimum) ;
Console.WriteLine( "Maximum : " + maximum );
} // Driver code
public static void Main()
{
int []arr = { 1, 2, 3, 4, 5, 6, 7 };
int n = arr.Length;
prime(arr, n);
}
} /* This code contributed by PrinciRaj1992 */ |
<script> // Javascript program to find minimum and maximum // prime number in given array. // Function to find count of prime function prime(arr, n)
{ // Find maximum value in the array
let max_val = arr.sort((b, a) => a - b)[0];
// 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 ;
}
}
// Minimum and Maximum prime number
let minimum = Number.MAX_SAFE_INTEGER;
let maximum = Number.MIN_SAFE_INTEGER;
for (let i = 0; i < n; i++)
if (prime[arr[i]]) {
minimum = Math.min(minimum, arr[i]);
maximum = Math.max(maximum, arr[i]);
}
document.write( "Minimum : " + minimum + "<br>" );
document.write( "Maximum : " + maximum + "<br>" );
} // Driver code let arr = [1, 2, 3, 4, 5, 6, 7]; let n = arr.length; prime(arr, n); // This code is contributed by Saurabh Jaiswal </script> |
Minimum : 2 Maximum : 7
Time complexity : O(n*log(log(n)))
Space Complexity: O(n)
Another Efficient Approach: (Using Map)
Another approach is to use for map to store all the elements in sorted order and then check for minimum and maximum prime numbers.
Steps:
To solve the problem do following steps:
- First create a map.
- Then iterate the array and insert the elements in map one by one.
- After iteration finishes, iterate the map 2 times and check for prime number one time from frontward and other time from backward.
- As soon as, find any prime number store and and exit from loop.
- After 2 iteration, return the minimum and maximum prime number.
Below is the implementation of the above approach:
// CPP program to find minimum and maximum // prime number in given array // using map #include <bits/stdc++.h> using namespace std;
// Function check whether a number // is prime or not bool isPrime( int n)
{ // Check if n=1 or n=0
if (n <= 1)
return false ;
// Check if n=2 or n=3
if (n == 2 || n == 3)
return true ;
// Check whether n is divisible by 2 or 3
if (n % 2 == 0 || n % 3 == 0)
return false ;
// Check from 5 to square root of n
// Iterate i by (i+6)
for ( int i = 5; i * i <= n; i += 6)
if (n % i == 0 || n % (i + 2) == 0)
return false ;
return true ;
} // Function to find minimum and maximum prime numbers void prime( int arr[], int n)
{ // To store minimum and maximum prime numbers
int maxx = -1, minn = -1;
// Create map
map< int , int > mp;
// Iterate to store elements in map
for ( int i = 0; i < n; i++) {
mp[arr[i]]++;
}
// Iterate to store minimum prime number
for ( auto it : mp) {
if (isPrime(it.first)) {
minn = it.first;
break ;
}
}
// Iterate in reverse order to store maximum prime
// number
for ( auto it = mp.rbegin(); it != mp.rend(); it++) {
if (isPrime(it->first)) {
maxx = it->first;
break ;
}
}
cout << "Minimum : " << minn << endl;
cout << "Maximum : " << maxx << endl;
} // Driver code int main()
{ int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
int n = sizeof (arr) / sizeof (arr[0]);
prime(arr, n);
return 0;
} // This code is contributed by Susobhan Akhuli |
import java.util.HashMap;
import java.util.Map;
public class Main {
// Function to check whether a number is prime or not
static boolean isPrime( int n) {
// Check if n=1 or n=0
if (n <= 1 )
return false ;
// Check if n=2 or n=3
if (n == 2 || n == 3 )
return true ;
// Check whether n is divisible by 2 or 3
if (n % 2 == 0 || n % 3 == 0 )
return false ;
// Check from 5 to square root of n
// Iterate i by (i+6)
for ( int i = 5 ; i * i <= n; i += 6 )
if (n % i == 0 || n % (i + 2 ) == 0 )
return false ;
return true ;
}
// Function to find minimum and maximum prime numbers
static void prime( int arr[], int n) {
// To store minimum and maximum prime numbers
int maxx = - 1 , minn = - 1 ;
// Create map
Map<Integer, Integer> mp = new HashMap<>();
// Iterate to store elements in map
for ( int i = 0 ; i < n; i++) {
mp.put(arr[i], mp.getOrDefault(arr[i], 0 ) + 1 );
}
// Iterate to store minimum prime number
for ( int i : arr) {
if (mp.get(i) > 0 && isPrime(i)) {
minn = i;
break ;
}
}
// Iterate in reverse order to store maximum prime number
for ( int i = n - 1 ; i >= 0 ; i--) {
if (mp.get(arr[i]) > 0 && isPrime(arr[i])) {
maxx = arr[i];
break ;
}
}
System.out.println( "Minimum : " + minn);
System.out.println( "Maximum : " + maxx);
}
// Driver code
public static void main(String[] args) {
int arr[] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 };
int n = arr.length;
prime(arr, n);
}
} // This code is contributed by Yash Agarwal |
# Function check whether a number # is prime or not def is_prime(n):
# Check if n=1 or n=0
if n < = 1 :
return False
# Check if n=2 or n=3
if n = = 2 or n = = 3 :
return True
# Check whether n is divisible by 2 or 3
if n % 2 = = 0 or n % 3 = = 0 :
return False
# Check from 5 to square root of n
# Iterate i by (i+6)
i = 5
while i * i < = n:
if n % i = = 0 or n % (i + 2 ) = = 0 :
return False
i + = 6
return True
# Function to find minimum and maximum prime numbers def prime(arr):
# To store minimum and maximum prime numbers
maxx = - 1
minn = - 1
# create a dictionary (similar to map in C++)
mp = {}
# Iterate to store elements in dictionary
for num in arr:
mp[num] = mp.get(num, 0 ) + 1
# Iterate to store minimum prime number
for num in sorted (mp):
if is_prime(num):
minn = num
break
# Iterate in reverse order to find maximum prime number
for num in sorted (mp, reverse = True ):
if is_prime(num):
maxx = num
break
print ( "Minimum:" , minn)
print ( "Maximum:" , maxx)
# Driver code if __name__ = = "__main__" :
arr = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ]
prime(arr)
|
using System;
using System.Collections.Generic;
public class MainClass
{ // Function to check whether a number is prime or not
static bool isPrime( int n)
{
// Check if n=1 or n=0
if (n <= 1)
return false ;
// Check if n=2 or n=3
if (n == 2 || n == 3)
return true ;
// Check whether n is divisible by 2 or 3
if (n % 2 == 0 || n % 3 == 0)
return false ;
// Check from 5 to square root of n
// Iterate i by (i+6)
for ( int i = 5; i * i <= n; i += 6)
if (n % i == 0 || n % (i + 2) == 0)
return false ;
return true ;
}
// Function to find minimum and maximum prime numbers
static void prime( int [] arr, int n)
{
// To store minimum and maximum prime numbers
int maxx = -1, minn = -1;
// Create dictionary
Dictionary< int , int > mp = new Dictionary< int , int >();
// Iterate to store elements in dictionary
for ( int i = 0; i < n; i++)
{
if (mp.ContainsKey(arr[i]))
mp[arr[i]]++;
else
mp[arr[i]] = 1;
}
// Iterate to store minimum prime number
foreach ( int i in arr)
{
if (mp[i] > 0 && isPrime(i))
{
minn = i;
break ;
}
}
// Iterate in reverse order to store maximum prime number
for ( int i = n - 1; i >= 0; i--)
{
if (mp[arr[i]] > 0 && isPrime(arr[i]))
{
maxx = arr[i];
break ;
}
}
Console.WriteLine( "Minimum : " + minn);
Console.WriteLine( "Maximum : " + maxx);
}
// Entry point
public static void Main( string [] args)
{
int [] arr = { 1, 2, 3, 4, 5, 6, 7 };
int n = arr.Length;
prime(arr, n);
}
} // This code is contributed by Yash Agarwal(yashagarwal2852002) |
// Function to check whether a number is prime or not function isPrime(n) {
if (n <= 1) return false ;
if (n == 2 || n == 3) return true ;
if (n % 2 == 0 || n % 3 == 0) return false ;
for (let i = 5; i * i <= n; i += 6)
if (n % i == 0 || n % (i + 2) == 0)
return false ;
return true ;
} // Function to find minimum and maximum prime numbers function findMinMaxPrimes(arr) {
let maxx = -1, minn = -1;
let mp = new Map();
for (let i = 0; i < arr.length; i++) {
if (mp.has(arr[i])) {
mp.set(arr[i], mp.get(arr[i]) + 1);
} else {
mp.set(arr[i], 1);
}
}
// Initialize minn and maxx with -1
for (let entry of mp.entries()) {
if (isPrime(entry[0])) {
minn = entry[0];
maxx = entry[0];
break ;
}
}
// Iterate to find minimum and maximum prime numbers
for (let entry of mp.entries()) {
if (isPrime(entry[0])) {
minn = Math.min(minn, entry[0]);
maxx = Math.max(maxx, entry[0]);
}
}
console.log( "Minimum : " + minn);
console.log( "Maximum : " + maxx);
} // Driver code let arr = [1, 2, 3, 4, 5, 6, 7]; findMinMaxPrimes(arr); |
Minimum : 2 Maximum : 7
Time complexity: O(n*sqrt(n)), to iterate n and to check for prime number is sqrt(n).
Auxiliary space: O(n), to store in map.