Nearest prime number in the array of every array element

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.

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

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.

#arrays #competitive programming #mathematical #hash #prime number #sieve

Nearest prime number in the array of every array element
7.60 GEEK