Check whether the number can be made perfect square after adding K
Last Updated :
16 Oct, 2022
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 = 7, K = 2
Output: Yes
Explanation:
7 + 2 = 9 which is a perfect square.
Input: N = 5, K = 3
Output: No
Explanation:
5 + 3 = 8 which is not a perfect square.
Approach: The idea is to compute the value of N + K and check if it is a perfect square or not. In order to check if a number is a perfect square or not, refer to this article.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void isPerfectSquare( long long int x)
{
long double sr = round( sqrt (x));
if (sr * sr == x)
cout << "Yes" ;
else
cout << "No" ;
}
int main()
{
int n = 7, k = 2;
isPerfectSquare(n + k);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static void isPerfectSquare( int x)
{
int sr = ( int )Math.sqrt(x);
if (sr * sr == x)
System.out.println( "Yes" );
else
System.out.println( "No" );
}
public static void main(String args[])
{
int n = 7 , k = 2 ;
isPerfectSquare(n + k);
}
}
|
Python3
from math import sqrt
def isPerfectSquare(x) :
sr = int (sqrt(x));
if (sr * sr = = x) :
print ( "Yes" );
else :
print ( "No" );
if __name__ = = "__main__" :
n = 7 ; k = 2 ;
isPerfectSquare(n + k);
|
C#
using System;
class GFG
{
static void isPerfectSquare( int x)
{
int sr = ( int )Math.Sqrt(x);
if (sr * sr == x)
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
public static void Main(String []args)
{
int n = 7;
int k = 2;
isPerfectSquare(n + k);
}
}
|
Javascript
<script>
function isPerfectSquare(x)
{
var sr = Math.round(Math.sqrt(x));
if (sr * sr == x)
document.write( "Yes" );
else
document.write( "No" );
}
var n = 7, k = 2;
isPerfectSquare(n + k);
</script>
|
Time complexity: O(log(N)), where N is sum of given n and k.
Auxiliary space: O(1)
Note: Similar, it can be checked whether (N – K) can be a perfect square or not, by replacing ‘+’ with ‘-‘ sign in the above function.
Share your thoughts in the comments
Please Login to comment...