Find the nearest perfect square for each element of the array | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void nearestPerfectSquare ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { int sr = sqrt ( arr [ i ] ) ; int a = sr * sr ; int b = ( sr + 1 ) * ( sr + 1 ) ; if ( ( arr [ i ] - a ) < ( b - arr [ i ] ) ) cout << a << " ▁ " ; else cout << b << " ▁ " ; } } int main ( ) { int arr [ ] = { 5 , 2 , 7 , 13 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; nearestPerfectSquare ( arr , N ) ; return 0 ; }