Find the nearest perfect square for each element of the array | Java program for the above approach ; 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
import java . io . * ; class GFG { static void nearestPerfectSquare ( int [ ] arr , int N ) { for ( int i = 0 ; i < N ; i ++ ) { int sr = ( int ) Math . sqrt ( arr [ i ] ) ; int a = sr * sr ; int b = ( sr + 1 ) * ( sr + 1 ) ; if ( ( arr [ i ] - a ) < ( b - arr [ i ] ) ) System . out . print ( a + " ▁ " ) ; else System . out . print ( b + " ▁ " ) ; } } public static void main ( String [ ] args ) { int [ ] arr = { 5 , 2 , 7 , 13 } ; int N = arr . length ; nearestPerfectSquare ( arr , N ) ; } }