How to check whether a number can be made a perfect square

Problem

Given two numbers n and k, the task is to check whether the given number n can be made a perfect square after adding k to it.

Examples

  • Input: n = 10, k = 6

  • Output: YES

Explanation: 10+6=1610 + 6 = 16, which is a perfect square of 44.

  • Input: n = 11, k = 8

  • Output: NO

Explanation: 11+8=1911 + 8 = 19, which is a not perfect square.

Solution

  • Add n and k (n+k), and then find the square root for n+k
  • Check if num_sqrt*num_sqrt = n+k
  • Print YES if it is a perfect square, otherwise print NO

Implementation in Python

In the following code snippet, we:

  • In line 1: Importing sqrt from module math to calculate square root.
  • In line 3 to 4: Initialize n and k with 10 and 6 respectively.
  • In line 6: Add k to n and store in num.
  • In line 8: Calculating the square root of num.
  • In line 10 to 13: Check for a perfect square.

It will print YES as 10+6=1610 + 6 = 16, square root 1616 is 44, and satisfies the condition for perfect square as 44=164 * 4 = 16.

from math import sqrt
#initialize N and K
N = 10
K = 6
#add K to N
num = N+K
#calculate square root
num_sqrt = int(sqrt(num))
#check for perfect square
if(num_sqrt * num_sqrt == num):
print("YES")
else:
print("NO")

The following code snippet also follows the same procedure as above except we changed the values for n and k.

It will print NO as 11+8=1911 + 8 = 19, which is not a perfect square. If we calculate square root for 1919, we get 44, which doesn’t satisfy the condition for perfect square. 44=164 * 4 = 16, not 1919.

from math import sqrt
#initialize N and K
N = 11
K = 8
#add K to N
num = N+K
#calculate square root
num_sqrt = int(sqrt(num))
#check for perfect square
if(num_sqrt * num_sqrt == num):
print("YES")
else:
print("NO")

Free Resources