Last Updated: 23 Jun, 2021

Closest Perfect Square

Easy
Asked in company
Nagarro Software

Problem statement

You are given a positive integer ‘N’. You are required to print the perfect square number closest to the ‘N’ and the number of steps required to reach that number.

For Example:
N = 21
The perfect square closest to 21 is 25, and the distance is 4. 
Input Format:
The first line contains a single integer ‘T’ denoting the number of test cases to be run. Then the test cases follow.

The first line of each test case contains a positive integer ‘N’ denoting the given number.
Output Format:
For each test case, You have to return a list of two integers such that the first number denotes the closest perfect square number, and the second number denotes its distance from ‘N’.

Output for each test case will be printed in a separate line.
Note
You are not required to print anything; it has already been taken care of. Just implement the function.
Constraints:
1 <= T <= 50
1 <= N <= 10^9

Time Limit: 1 sec.

Approaches

01 Approach

We will move in both directions, positive and negative, of ‘N’, and check if we get any perfect square.

Algorithm:

  1. Initiate a variable i = 0 .
  2. Iterate from
    1. Start a loop and keep adding and subtracting ‘i’ in ‘N’ and check for a perfect square.
    2. To check for a perfect square, you can use a for loop starting from (say) ‘j’ = 1 and less than that number (X) and check if( j * j == X). if equal, return true and break the loop.
    3. Now increase the value of ‘i’ by 1 in each iteration.

02 Approach

Find the square root of 'N'. Let it be ‘X’. Now check the distance between the square of ‘X’ and ‘N’ and the square of ('X' + ‘1’ ) and ‘N’.


Algorithm:

 

  1. Declare a variable ‘X’ of type int to store the square root of ‘N’.
  2. Compare the Distance between the square of ‘X’ and ‘N’ and the square of ‘X + 1’ and ‘N’.
  3. If the distance of ‘N’ from the square of ‘X’ is less than the distance of ‘N’ from the square of ‘X + 1’ then return X and abs(N - (X * X)).
  4. Otherwise return ‘X+1’and abs( N - (X+1) * (X + 1)).