Find the nearest perfect square for each element of the array | Function to find the nearest perfect square for every element in the given array import the math module ; Traverse the array ; Calculate square root of current element ; Calculate perfect square ; Find the nearest ; Driver Code
import math NEW_LINE def nearestPerfectSquare ( arr , N ) : NEW_LINE INDENT for i in range ( 0 , N ) : NEW_LINE INDENT sr = math . floor ( math . sqrt ( arr [ i ] ) ) NEW_LINE a = sr * sr NEW_LINE b = ( sr + 1 ) * ( sr + 1 ) NEW_LINE if ( ( arr [ i ] - a ) < ( b - arr [ i ] ) ) : NEW_LINE print ( a , end = " ▁ " ) NEW_LINE else : NEW_LINE print ( b , end = " ▁ " ) NEW_LINE DEDENT DEDENT arr = [ 5 , 2 , 7 , 13 ] NEW_LINE N = len ( arr ) NEW_LINE nearestPerfectSquare ( arr , N ) NEW_LINE