Skip to content
Related Articles

Related Articles

Find the nearest perfect square for each element of the array

View Discussion
Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 13 Sep, 2021
View Discussion
Improve Article
Save Article

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[0] (= 5) is 4.
The nearest perfect square of arr[1] (= 2) is 1.
The nearest perfect square of arr[2] (= 7) is 9.
The nearest perfect square of arr[3] (= 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 <bits/stdc++.h>
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[0]);
    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




<script>
 
// JavaScript program for the above approach
 
// Function to find the nearest perfect square
// for every element in the given array
function nearestPerfectSquare(arr, N)
{
 
    // Traverse the array
    for (let i = 0; i < N; i++) {
 
        // Calculate square root of
        // current  element
        let sr = parseInt(Math.sqrt(arr[i]));
 
        // Calculate perfect square
        let a = sr * sr;
        let b = (sr + 1) * (sr + 1);
 
        // Find the nearest
        if ((arr[i] - a) < (b - arr[i]))
            document.write(a + " ");
        else
            document.write(b + " ");
    }
}
 
// Driver Code
    let arr = [ 5, 2, 7, 13 ];
    let N = arr.length;
    nearestPerfectSquare(arr, N);
     
</script>

Output: 

4 1 9 16

 

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

Auxiliary Space: O(1) 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!