Nearest prime number in the array of every array element | Python3 program to find nearest prime number in the array for all array elements ; 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 ; Sieve of Eratosthenes function ; 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 . ; Function to find nearest prime number for all elements ; Compute and store all prime numbers up to maxm ; Store the indices of all primes ; If no primes are present in the array ; Store the current prime ; If the no further primes exist in the array ; For all indices less than that of the current prime ; If the current prime is nearer ; If the next prime is nearer ; Make the next prime as the current ; Driver code
maxi = 10000000 NEW_LINE prime = [ False ] * ( maxi ) NEW_LINE def SieveOfEratosthenes ( maxm ) : NEW_LINE INDENT prime [ 0 ] = prime [ 1 ] = True NEW_LINE for i in range ( 2 , maxm + 1 ) : NEW_LINE INDENT if i * i > maxm : NEW_LINE INDENT break NEW_LINE DEDENT if ( not prime [ i ] ) : NEW_LINE INDENT for j in range ( i * i , maxm + 1 , i ) : NEW_LINE INDENT prime [ j ] = True NEW_LINE DEDENT DEDENT DEDENT DEDENT def print_nearest_prime ( arr , N ) : NEW_LINE INDENT maxm = max ( arr ) NEW_LINE SieveOfEratosthenes ( maxm ) NEW_LINE primes = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( not prime [ arr [ i ] ] ) : NEW_LINE INDENT primes . append ( i ) NEW_LINE DEDENT DEDENT if len ( primes ) == 0 : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT print ( - 1 , end = " ▁ " ) NEW_LINE DEDENT return NEW_LINE DEDENT curr = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( curr == len ( primes ) - 1 or i <= primes [ curr ] ) : NEW_LINE INDENT print ( arr [ primes [ curr ] ] , end = " ▁ " ) NEW_LINE continue NEW_LINE DEDENT if ( abs ( primes [ curr ] - i ) < abs ( primes [ curr + 1 ] - i ) ) : NEW_LINE INDENT print ( arr [ primes [ curr ] ] , end = " ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT curr += 1 NEW_LINE print ( arr [ primes [ curr ] ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 6 NEW_LINE arr = [ 8 , 7 , 12 , 15 , 3 , 11 ] NEW_LINE print_nearest_prime ( arr , N ) NEW_LINE DEDENT