Friday, March 5, 2021

Published March 05, 2021 by Anonymous with 0 comment

Find the nearest odd and even perfect squares of odd and even array elements respectively

Find the nearest odd and even perfect squares of odd and even array elements respectively

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;

}

Output:
4 1 4 9

Time Complexity: O(N *  M)
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.

Let's block ads! (Why?)

      edit

0 comments:

Post a Comment