Closest Perfect Square

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.
CodingNinjas
author
2y

Approach :

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’ f...read more

CodingNinjas
author
2y
Naive 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 s...read more
CodingNinjas
author
2y
Square Root

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 ...read more
Add answer anonymously...
Nagarro Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter