Check whether the number can be made perfect square after adding 1
Last Updated :
16 Oct, 2022
Given an integer N, the task is to check whether N the given number can be made a perfect square after adding 1 to it.
Examples:
Input: 3
Output: Yes
3 + 1 = 4 which is a perfect square i.e. 22
Input: 5
Output: No
5 + 1 = 6 which is not a perfect square.
Approach: Check whether n + 1 is a perfect square or not by taking the square root of n + 1 and checking whether it is an integer. If it is then n + 1 is a perfect square and n is a sunny number.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool isPerfectSquare( long double x)
{
long double sr = sqrt (x);
return ((sr - floor (sr)) == 0);
}
bool isSunnyNum( int n)
{
if (isPerfectSquare(n + 1))
return true ;
return false ;
}
int main()
{
int n = 3;
if (isSunnyNum(n))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
class GFG
{
static boolean isPerfectSquare( double x)
{
double sr = Math.sqrt(x);
return ((sr - Math.floor(sr)) == 0 );
}
static boolean isSunnyNum( int n)
{
if (isPerfectSquare(n + 1 ))
return true ;
return false ;
}
public static void main (String[] args)
{
int n = 3 ;
if (isSunnyNum(n))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
import math as mt
def isPerfectSquare(x):
sr = mt.sqrt(x)
return ((sr - mt.floor(sr)) = = 0 )
def isSunnyNum(n):
if (isPerfectSquare(n + 1 )):
return True
return False
n = 3
if (isSunnyNum(n)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG
{
static bool isPerfectSquare( double x)
{
double sr = Math.Sqrt(x);
return ((sr - Math.Floor(sr)) == 0);
}
static bool isSunnyNum( int n)
{
if (isPerfectSquare(n + 1))
return true ;
return false ;
}
public static void Main ()
{
int n = 3;
if (isSunnyNum(n))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
PHP
<?php
function isPerfectSquare( $x )
{
$sr = sqrt( $x );
return (( $sr - floor ( $sr )) == 0);
}
function isSunnyNum( $n )
{
if (isPerfectSquare( $n + 1))
return true;
return false;
}
$n = 3;
if (isSunnyNum( $n ))
echo "Yes" ;
else
echo "No" ;
?>
|
Javascript
<script>
function isPerfectSquare(x)
{
let sr = Math.sqrt(x);
return ((sr - Math.floor(sr)) == 0);
}
function isSunnyNum(n)
{
if (isPerfectSquare(n + 1))
return true ;
return false ;
}
let n = 3;
if (isSunnyNum(n))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity: O(logn)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...