📌  相关文章
📜  查找大于给定数字的下一个完美平方

📅  最后修改于: 2021-04-23 18:07:55             🧑  作者: Mango

给定数字N,任务是找到下一个大于N的理想平方。
例子

Input: N = 6
Output: 9
9 is a greater number than 6 and
is also a perfect square

Input: N = 9
Output: 16

方法:

  1. 找出给定N的平方根。
  2. 使用C++中的下限函数计算其下限值。
  3. 然后添加1。
  4. 打印该数字的正方形。

下面是上述方法的实现:

C++
// C++ implementation of above approach
#include 
#include
using namespace std;
 
// Function to find the next perfect square
int nextPerfectSquare(int N)
{
    int nextN = floor(sqrt(N)) + 1;
 
    return nextN * nextN;
}
 
// Driver Code
int main()
{
    int n = 35;
 
    cout << nextPerfectSquare(n);
    return 0;
}


Java
// Java implementation of above approach
import java.util.*;
import java.lang.*;
import java.io.*;
 
class GFG
{
     
// Function to find the
// next perfect square
static int nextPerfectSquare(int N)
{
    int nextN = (int)Math.floor(Math.sqrt(N)) + 1;
 
    return nextN * nextN;
}
 
// Driver Code
public static void main(String args[])
{
    int n = 35;
 
    System.out.println (nextPerfectSquare(n));
}
}
 
// This code is contributed by Subhadeep


Python3
# Python3 implementation of above approach
 
import math
#Function to find the next perfect square
 
def nextPerfectSquare(N):
 
    nextN = math.floor(math.sqrt(N)) + 1
 
    return nextN * nextN
 
if __name__=='__main__':
    N = 35
    print(nextPerfectSquare(N))
 
# this code is contributed by Surendra_Gangwar


C#
// C# implementation of above approach
using System;
 
class GFG
{
     
// Function to find the
// next perfect square
static int nextPerfectSquare(int N)
{
    int nextN = (int)Math.Floor(Math.Sqrt(N)) + 1;
 
    return nextN * nextN;
}
 
// Driver Code
public static void Main()
{
    int n = 35;
 
    Console.WriteLine(nextPerfectSquare(n));
}
}
 
// This code is contributed
// by Shashank


PHP


Javascript


输出:
36

时间复杂度: O(1)

辅助空间: O(1)