Find the nearest odd and even perfect squares of odd and even array elements respectively
Last Updated :
17 Sep, 2022
Given an array arr[ ] of size N, the task for each array element is to print the nearest perfect square having same parity.
Examples:
Input: arr[ ] = {6, 3, 2, 15}
Output: 4 1 4 9
Explanation:
The nearest even perfect square of arr[0] (= 6) is 4.
The nearest odd perfect square of arr[1] (= 3) is 1.
The nearest even perfect square of arr[2] (= 2) is 4
The nearest odd perfect square of arr[3] (= 15) is 9.
Input: arr[ ] = {31, 18, 64}
Output: 25 16 64
Approach: Follow the steps below to solve the problem:
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void nearestPerfectSquare( int arr[], int N)
{
for ( int i = 0; i < N; i++) {
int sr = sqrt (arr[i]);
if ((sr & 1) == (arr[i] & 1))
cout << sr * sr << " " ;
else {
sr++;
cout << sr * sr << " " ;
}
}
}
int main()
{
int arr[] = { 6, 3, 2, 15 };
int N = sizeof (arr) / sizeof (arr[0]);
nearestPerfectSquare(arr, N);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static void nearestPerfectSquare( int arr[], int N)
{
for ( int i = 0 ; i < N; i++) {
int sr = ( int )Math.sqrt(arr[i]);
if ((sr & 1 ) == (arr[i] & 1 ))
System.out.print((sr * sr) + " " );
else {
sr++;
System.out.print((sr * sr) + " " );
}
}
}
public static void main(String[] args)
{
int arr[] = { 6 , 3 , 2 , 15 };
int N = arr.length;
nearestPerfectSquare(arr, N);
}
}
|
Python3
import math
def nearestPerfectSquare(arr, N) :
for i in range (N):
sr = int (math.sqrt(arr[i]))
if ((sr & 1 ) = = (arr[i] & 1 )) :
print (sr * sr, end = " " )
else :
sr + = 1
print (sr * sr, end = " " )
arr = [ 6 , 3 , 2 , 15 ]
N = len (arr)
nearestPerfectSquare(arr, N)
|
C#
using System;
class GFG{
static void nearestPerfectSquare( int [] arr, int N)
{
for ( int i = 0; i < N; i++) {
int sr = ( int )Math.Sqrt(arr[i]);
if ((sr & 1) == (arr[i] & 1))
Console.Write((sr * sr) + " " );
else {
sr++;
Console.Write((sr * sr) + " " );
}
}
}
static public void Main()
{
int [] arr = { 6, 3, 2, 15 };
int N = arr.Length;
nearestPerfectSquare(arr, N);
}
}
|
Javascript
<script>
function nearestPerfectSquare(arr, N)
{
for (let i = 0; i < N; i++)
{
let sr = Math.floor(Math.sqrt(arr[i]));
if ((sr & 1) == (arr[i] & 1))
document.write((sr * sr) + " " );
else
{
sr++;
document.write((sr * sr) + " " );
}
}
}
let arr = [ 6, 3, 2, 15 ];
let N = arr.length;
nearestPerfectSquare(arr, N);
</script>
|
Time Complexity: O(N*logN) where N is size of given array
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...