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 ; Traverse the array ; Calculate square root of current element ; Calculate perfect square ; Find the nearest ; Driver Code
function nearestPerfectSquare ( arr , N ) { for ( let i = 0 ; i < N ; i ++ ) { let sr = parseInt ( Math . sqrt ( arr [ i ] ) ) ; let a = sr * sr ; let b = ( sr + 1 ) * ( sr + 1 ) ; if ( ( arr [ i ] - a ) < ( b - arr [ i ] ) ) document . write ( a + " " ) ; else document . write ( b + " " ) ; } } let arr = [ 5 , 2 , 7 , 13 ] ; let N = arr . length ; nearestPerfectSquare ( arr , N ) ;