Find the Next perfect square greater than a given number
Last Updated :
25 Sep, 2022
Given a number N, the task is to find the next perfect square greater than N.
Examples:
Input: N = 6
Output: 9
Explanation: 9 is a greater number than 6 and is also a perfect square
Input: N = 9
Output: 16
Approach:
- Find the square root of given N.
- Calculate its floor value using floor function in C++.
- Then add 1 to it.
- Print square of that number.
Below is the implementation of above approach:
C++
#include <iostream>
#include<cmath>
using namespace std;
int nextPerfectSquare( int N)
{
int nextN = floor ( sqrt (N)) + 1;
return nextN * nextN;
}
int main()
{
int n = 35;
cout << nextPerfectSquare(n);
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
static int nextPerfectSquare( int N)
{
int nextN = ( int )Math.floor(Math.sqrt(N)) + 1 ;
return nextN * nextN;
}
public static void main(String args[])
{
int n = 35 ;
System.out.println (nextPerfectSquare(n));
}
}
|
Python3
import math
def nextPerfectSquare(N):
nextN = math.floor(math.sqrt(N)) + 1
return nextN * nextN
if __name__ = = '__main__' :
N = 35
print (nextPerfectSquare(N))
|
C#
using System;
class GFG
{
static int nextPerfectSquare( int N)
{
int nextN = ( int )Math.Floor(Math.Sqrt(N)) + 1;
return nextN * nextN;
}
public static void Main()
{
int n = 35;
Console.WriteLine(nextPerfectSquare(n));
}
}
|
PHP
<?php
function nextPerfectSquare( $N )
{
$nextN = floor (sqrt( $N )) + 1;
return $nextN * $nextN ;
}
$n = 35;
echo nextPerfectSquare( $n );
?>
|
Javascript
<script>
function nextPerfectSquare(N)
{
let nextN = Math.floor(Math.sqrt(N)) + 1;
return nextN * nextN;
}
let n = 35;
document.write(nextPerfectSquare(n));
</script>
|
Time Complexity: O(logn) for given number n, as it is using inbuilt sqrt function
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...