Minimum and Maximum prime numbers in an array

21 May, 2021
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 sieve of Eratosthenes and store them in a hash. Now traverse the array and find the minimum and maximum element which are prime using the hash table.Below is the implementation of above approach:  
C++
Java
Python3
C#
Javascript
// CPP program to find minimum and maximum// prime number in given array.#include <bits/stdc++.h>using namespace std; // Function to find count of primevoid 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 codeint 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 primestatic 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 primedef 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 codearr = [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 primestatic 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 primefunction 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))) 
29AjayKumar
VishalBachchas
mohit kumar 29
princiraj1992
_saurabh_jaiswal
Prime Number
sieve
Technical Scripter 2018
Arrays
Technical Scripter
Arrays
Prime Number
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in Java
Introduction to Arrays
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
K'th Smallest/Largest Element in Unsorted Array | Set 1
Subset Sum Problem | DP-25
Python | Using 2D arrays/lists the right way
Introduction to Data Structures
Find Second largest element in an array
Search an element in a sorted and rotated array
Find the Missing Number