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.
Input: n = 10
, k = 6
Output: YES
Explanation: $10 + 6 = 16$, which is a perfect square of $4$.
Input: n = 11
, k = 8
Output: NO
Explanation: $11 + 8 = 19$, which is a not perfect square.
n
and k
(n+k
), and then find the square root for n+k
num_sqrt
*num_sqrt
= n+k
YES
if it is a perfect square, otherwise print NO
In the following code snippet, we:
sqrt
from module math
to calculate square root.n
and k
with 10
and 6
respectively.k
to n
and store in num
.num
.It will print YES
as $10 + 6 = 16$, square root $16$ is $4$, and satisfies the condition for perfect square as $4 * 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 = 19$, which is not a perfect square. If we calculate square root for $19$, we get $4$, which doesn’t satisfy the condition for perfect square. $4 * 4 = 16$, not $19$.
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")
RELATED TAGS
CONTRIBUTOR
View all Courses