Given an integer array arr[] consisting of N integers, the task is to find the nearest Prime Number in the array for every element in the array. If the array does not contain any prime number, then print -1.
Examples:
Input: arr[] = {1, 2, 3, 1, 6}
Output: 2 2 3 3 3
Explanation:
For the subarray {1, 2}, the nearest prime number is 2.
For the subarray {3, 1, 6}, the nearest prime number is 3.Input: arr[] = {8, 7, 12, 15, 3, 11}
Output: 7 7 7 3 3 11
Explanation:
For the subarray {8, 7, 12}, the nearest prime number is 7.
For the subarray {15, 3}, the nearest prime number is 3.
For the subarray {11}, the nearest prime number is 11 itself.
Approach:
Follow the steps below to solve the problem:
- Find the maximum element maxm in the array.
- Compute and store all prime numbers up to maxm using Sieve of Eratosthenes
- Traverse the array and store the indices of the prime numbers.
- If no prime numbers are present in the array, print -1 for all indices.
- Point curr to the first index consisting of a prime number.
- For every index up to curr, print the arr[primes[curr]] as the nearest prime number.
- For indices exceeding curr, compare the distance with primes[curr] and primes[curr + 1]. If primes[curr] is nearer, print arr[primes[curr]]. Otherwise, increment curr nad print arr[primes[curr]].
- If curr is the last prime in the array, print arr[primes[curr]] for all indices onwards.
Below is the implementation of the above approach:
C++
// C++ program to find nearest // prime number in the array // for all array elements #include <bits/stdc++.h> using namespace std; #define max 10000000 // Create a boolean array and set all // entries it as false. A value in // prime[i] will be true if i is not a // prime, else false bool prime[max] = { false }; // Sieve of Eratosthenes function void SieveOfEratosthenes(int maxm) { prime[0] = prime[1] = true; for (int i = 2; i * i <= maxm; i++) { // Update all multiples of i greater // than or equal to the square of it // numbers which are multiple of i and are // less than i^2 are already been marked. if (!prime[i]) { for (int j = i * i; j <= maxm; j += i) { prime[j] = true; } } } } // Function to find nearest // prime number for all elements void print_nearest_prime(int arr[], int N) { int maxm = *max_element(arr, arr + N); // Compute and store all prime // numbers up to maxm SieveOfEratosthenes(maxm); vector<int> primes; for (int i = 0; i < N; i++) { // Store the indices of // all primes if (!prime[arr[i]]) primes.push_back(i); } // If no primes are present // in the array if (primes.size() == 0) { for (int i = 0; i < N; i++) { cout << -1 << " "; } return; } // Store the current prime int curr = 0; for (int i = 0; i < N; i++) { // If the no further // primes exist in the array if (curr == primes.size() - 1 // For all indices less than // that of the current prime || i <= primes[curr]) { cout << arr[primes[curr]] << " "; continue; } // If the current prime is // nearer if (abs(primes[curr] - i) < abs(primes[curr + 1] - i)) { cout << arr[primes[curr]] << " "; } // If the next prime is nearer else { // Make the next prime // as the current curr++; cout << arr[primes[curr]] << " "; } } } // Driver Program int main() { int N = 6; int arr[] = { 8, 7, 12, 15, 3, 11 }; print_nearest_prime(arr, N); return 0; } |
Java
// Java program to find nearest // prime number in the array // for all array elements import java.util.*; class GFG{ static final int max = 10000000; // Create a boolean array and set all // entries it as false. A value in // prime[i] will be true if i is not a // prime, else false static boolean []prime = new boolean[max]; // Sieve of Eratosthenes function static void SieveOfEratosthenes(int maxm) { prime[0] = prime[1] = true; for(int i = 2; i * i <= maxm; i++) { // Update all multiples of i greater // than or equal to the square of it // numbers which are multiple of i // and are less than i^2 are already // been marked. if (!prime[i]) { for(int j = i * i; j <= maxm; j += i) { prime[j] = true; } } } } // Function to find nearest // prime number for all elements static void print_nearest_prime(int arr[], int N) { int maxm = Arrays.stream(arr).max().getAsInt(); // Compute and store all prime // numbers up to maxm SieveOfEratosthenes(maxm); Vector<Integer> primes = new Vector<Integer>(); for(int i = 0; i < N; i++) { // Store the indices of // all primes if (!prime[arr[i]]) primes.add(i); } // If no primes are present // in the array if (primes.size() == 0) { for(int i = 0; i < N; i++) { System.out.print(-1 + " "); } return; } // Store the current prime int curr = 0; for(int i = 0; i < N; i++) { // If the no further // primes exist in the array if (curr == primes.size() - 1 || // For all indices less than // that of the current prime i <= primes.get(curr)) { System.out.print( arr[primes.get(curr)] + " "); continue; } // If the current prime is // nearer if (Math.abs(primes.get(curr) - i) < Math.abs(primes.get(curr + 1) - i)) { System.out.print( arr[primes.get(curr)] + " "); } // If the next prime is nearer else { // Make the next prime // as the current curr++; System.out.print( arr[primes.get(curr)] + " "); } } } // Driver code public static void main(String[] args) { int N = 6; int arr[] = { 8, 7, 12, 15, 3, 11 }; print_nearest_prime(arr, N); } } // This code is contributed by PrinciRaj1992 |
Python3
# Python3 program to find nearest # prime number in the array # for all array elements maxi = 10000000 # Create a boolean array and set all # entries it as false. A value in # prime[i] will be true if i is not a # prime, else false prime = [False] * (maxi) # Sieve of Eratosthenes function def SieveOfEratosthenes(maxm): prime[0] = prime[1] = True for i in range(2, maxm + 1): if i * i > maxm: break # Update all multiples of i greater # than or equal to the square of it # numbers which are multiple of i and are # less than i^2 are already been marked. if (not prime[i]): for j in range(i * i, maxm + 1, i): prime[j] = True # Function to find nearest # prime number for all elements def print_nearest_prime(arr, N): maxm = max(arr) # Compute and store all prime # numbers up to maxm SieveOfEratosthenes(maxm) primes = [] for i in range(N): # Store the indices of # all primes if (not prime[arr[i]]): primes.append(i) # If no primes are present # in the array if len(primes) == 0: for i in range(N): print(-1, end = " ") return # Store the current prime curr = 0 for i in range(N): # If the no further primes # exist in the array if (curr == len(primes) - 1 or # For all indices less than # that of the current prime i <= primes[curr]): print(arr[primes[curr]], end = " ") continue # If the current prime is # nearer if (abs(primes[curr] - i) < abs(primes[curr + 1] - i)): print(arr[primes[curr]], end = " ") # If the next prime is nearer else: # Make the next prime # as the current curr += 1 print(arr[primes[curr]], end = " ") # Driver code if __name__ == '__main__': N = 6 arr = [ 8, 7, 12, 15, 3, 11 ] print_nearest_prime(arr, N) # This code is contributed by mohit kumar 29 |
C#
// C# program to find nearest // prime number in the array // for all array elements using System; using System.Linq; using System.Collections.Generic; class GFG{ static readonly int max = 10000000; // Create a bool array and set all // entries it as false. A value in // prime[i] will be true if i is not a // prime, else false static bool []prime = new bool[max]; // Sieve of Eratosthenes function static void SieveOfEratosthenes(int maxm) { prime[0] = prime[1] = true; for(int i = 2; i * i <= maxm; i++) { // Update all multiples of i greater // than or equal to the square of it // numbers which are multiple of i // and are less than i^2 are already // been marked. if (!prime[i]) { for(int j = i * i; j <= maxm; j += i) { prime[j] = true; } } } } // Function to find nearest // prime number for all elements static void print_nearest_prime(int []arr, int N) { int maxm = arr.Max(); // Compute and store all prime // numbers up to maxm SieveOfEratosthenes(maxm); List<int> primes = new List<int>(); for(int i = 0; i < N; i++) { // Store the indices of // all primes if (!prime[arr[i]]) primes.Add(i); } // If no primes are present // in the array if (primes.Count == 0) { for(int i = 0; i < N; i++) { Console.Write(-1 + " "); } return; } // Store the current prime int curr = 0; for(int i = 0; i < N; i++) { // If the no further // primes exist in the array if (curr == primes.Count - 1 || // For all indices less than // that of the current prime i <= primes[curr]) { Console.Write( arr[primes[curr]] + " "); continue; } // If the current prime is // nearer if (Math.Abs(primes[curr] - i) < Math.Abs(primes[curr + 1] - i)) { Console.Write( arr[primes[curr]] + " "); } // If the next prime is nearer else { // Make the next prime // as the current curr++; Console.Write( arr[primes[curr]] + " "); } } } // Driver code public static void Main(String[] args) { int N = 6; int []arr = { 8, 7, 12, 15, 3, 11 }; print_nearest_prime(arr, N); } } // This code is contributed by PrinciRaj1992 |
7 7 7 3 3 11
Time Complexity: O(maxm * (log(log(maxm))) + N)
Auxiliary Space: O(N)
Recommended Posts:
- Print the nearest prime number formed by adding prime numbers to N
- Nearest element with at-least one common prime factor
- Count occurrences of a prime number in the prime factorization of every element from the given range
- Nearest prime less than given number n
- Longest subsequence such that every element in the subsequence is formed by multiplying previous element with a prime
- Maximize length of increasing subsequence possible by replacing array element by nearest primes
- Count decrements to nearest smaller element required to make all array elements equal
- Largest element smaller than current element on left for every element in Array
- Print numbers such that no two consecutive numbers are co-prime and every three consecutive numbers are co-prime
- Nearest smaller number to N having multiplicative inverse under modulo N equal to that number
- First element of every K sets having consecutive elements with exactly K prime factors less than N
- Round the given number to nearest multiple of 10
- Nearest greater number by interchanging the digits
- Round the given number to nearest multiple of 10 | Set-2
- Closest greater element for every array element from another array
- Find the nearest smaller numbers on left side in an array
- Nearest smaller character to a character K from a Sorted Array
- Sum of each element raised to (prime-1) % prime
- Sum of every K'th prime number in an array
- Product of every K’th prime number in an array
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


