Related Articles

# Find the nearest perfect square for each element of the array

• Difficulty Level : Basic
• Last Updated : 13 Sep, 2021

Given an array arr[] consisting of N positive integers, the task is to print the nearest perfect square for each array element.

Examples:

Input: arr[] = {5, 2, 7, 13}
Output: 4 1 9 16
Explanation:
The nearest perfect square of arr (= 5) is 4.
The nearest perfect square of arr (= 2) is 1.
The nearest perfect square of arr (= 7) is 9.
The nearest perfect square of arr (= 13) is 16.

Input: arr[] = {31, 18, 64}
Output: 36 16 64

Approach: Follow the steps below to solve the problem:

• Traverse the array from left to right.
• For every array element, find the nearest perfect square
• If N is a perfect square then print N
• Else, find the first perfect square number > N and note its difference with N.
• Then, find the first perfect square number < N and note its difference with N.
• And print the perfect square resulting in the minimum of these two differences obtained

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach` `#include ``using` `namespace` `std;` `// Function to find the nearest perfect square``// for every element in the given array``void` `nearestPerfectSquare(``int` `arr[], ``int` `N)``{` `    ``// Traverse the array``    ``for` `(``int` `i = 0; i < N; i++) {` `        ``// Calculate square root of``        ``// current  element``        ``int` `sr = ``sqrt``(arr[i]);` `        ``// Calculate perfect square``        ``int` `a = sr * sr;``        ``int` `b = (sr + 1) * (sr + 1);` `        ``// Find the nearest``        ``if` `((arr[i] - a) < (b - arr[i]))``            ``cout << a << ``" "``;``        ``else``            ``cout << b << ``" "``;``    ``}``}` `// Driver Code``int` `main()``{``    ``int` `arr[] = { 5, 2, 7, 13 };``    ``int` `N = ``sizeof``(arr) / ``sizeof``(arr);``    ``nearestPerfectSquare(arr, N);``    ``return` `0;``}`

## Java

 `// Java program for the above approach``import` `java.io.*;` `class` `GFG{` `// Function to find the nearest perfect square``// for every element in the given array``static` `void` `nearestPerfectSquare(``int``[] arr, ``int` `N)``{``    ` `    ``// Traverse the array``    ``for``(``int` `i = ``0``; i < N; i++)``    ``{``        ` `        ``// Calculate square root of``        ``// current  element``        ``int` `sr = (``int``)Math.sqrt(arr[i]);` `        ``// Calculate perfect square``        ``int` `a = sr * sr;``        ``int` `b = (sr + ``1``) * (sr + ``1``);` `        ``// Find the nearest``        ``if` `((arr[i] - a) < (b - arr[i]))``            ``System.out.print(a + ``" "``);``        ``else``            ``System.out.print(b + ``" "``);``    ``}``}` `// Driver Code``public` `static` `void` `main(String[] args)``{``    ``int``[] arr = { ``5``, ``2``, ``7``, ``13` `};``    ``int` `N = arr.length;``    ` `    ``nearestPerfectSquare(arr, N);``}``}` `// This code is contributed by souravmahato348`

## Python3

 `# Python program for the above approach``# Function to find the nearest perfect square``# for every element in the given array``# import the math module``import` `math``def` `nearestPerfectSquare(arr,N):``    ` `    ``# Traverse the array``    ``for` `i ``in` `range``(``0``,N):` `        ``# Calculate square root of``        ``# current  element``        ``sr ``=` `math.floor(math.sqrt(arr[i]))` `        ``# Calculate perfect square``        ``a ``=` `sr ``*` `sr``        ``b ``=` `(sr ``+` `1``) ``*` `(sr ``+` `1``)` `        ``# Find the nearest``        ``if` `((arr[i] ``-` `a) < (b ``-` `arr[i])):``           ``print``(a ,end``=``" "``)``        ``else` `:``           ``print``(b ,end``=``" "``)``        ` `# Driver Code``arr ``=`  `[``5``, ``2``, ``7``, ``13``]``N ``=` `len``(arr)``nearestPerfectSquare(arr, N)``    ` `# This code is contributed by shivanisinghss2110`

## C#

 `// C# program for the above approach``using` `System;``class` `GFG``{` `    ``// Function to find the nearest perfect square``    ``// for every element in the given array``    ``static` `void` `nearestPerfectSquare(``int``[] arr, ``int` `N)``    ``{` `        ``// Traverse the array``        ``for` `(``int` `i = 0; i < N; i++) {` `            ``// Calculate square root of``            ``// current  element``            ``int` `sr = (``int``)Math.Sqrt(arr[i]);` `            ``// Calculate perfect square``            ``int` `a = sr * sr;``            ``int` `b = (sr + 1) * (sr + 1);` `            ``// Find the nearest``            ``if` `((arr[i] - a) < (b - arr[i]))``                ``Console.Write(a + ``" "``);``            ``else``                ``Console.Write(b + ``" "``);``        ``}``    ``}` `    ``// Driver Code``    ``public` `static` `void` `Main()``    ``{``        ``int``[] arr = { 5, 2, 7, 13 };``        ``int` `N = arr.Length;` `        ``nearestPerfectSquare(arr, N);``    ``}``}` `// This code is contributed by souravmahato348`

## Javascript

 ``
Output:
`4 1 9 16`

Time Complexity: O(N * sqrt(arr[i]))

Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up