📜  找到一对具有差 K 的连续完美平方

📅  最后修改于: 2022-05-13 01:56:06.077000             🧑  作者: Mango

找到一对具有差 K 的连续完美平方

给定一个整数K ,任务是找到两个差为K的连续完美正方形。如果不存在任何这样的数字对,则打印-1

例子:

朴素方法:解决给定问题的简单方法是遍历所有完美正方形并检查是否存在差为K的任何 2 个这样的数字,如果发现为真,则打印这些对。否则,打印-1

时间复杂度: O(N)
辅助空间: O(1)

有效方法:上述方法也可以通过观察连续完美正方形之间的差异来优化:

从上面的观察可以看出,连续的完全平方之间的差是连续奇数的顺序。因此,当差为偶数时,则不存在这样的数字对,因此打印“-1” 。否则,这两个数字由(K/2) 2((K + 1)/2) 2给出。

下面是上述方法的实现:

C++14
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find two consecutive
// perfect square numbers whose
// difference is N
void findPrimeNumbers(int N)
{
    int a, b;
    a = (N / 2) * (N / 2);
    b = ((N + 1) / 2) * ((N + 1) / 2);
 
    if ((N % 2) == 0)
        cout << "-1";
    else
        cout << a << " " << b;
}
 
// Driver Code
int main()
{
    int K = 5;
    findPrimeNumbers(K);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
 
class GFG {
 
    // Function to find two consecutive
    // perfect square numbers whose
    // difference is N
    static void findPrimeNumbers(int N)
    {
        int a, b;
        a = (N / 2) * (N / 2);
        b = ((N + 1) / 2) * ((N + 1) / 2);
 
        if ((N % 2) == 0)
            System.out.println("-1");
        else
            System.out.println(a + " " + b);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int K = 5;
        findPrimeNumbers(K);
    }
}
 
// This code is contributed by Dharanendra L V.


Python3
# python program for the above approach
 
# Function to find two consecutive
# perfect square numbers whose
# difference is N
def findPrimeNumbers(N):
    a = (N // 2) * (N // 2)
    b = ((N + 1) // 2) * ((N + 1) // 2)
 
    if ((N % 2) == 0):
        print("-1")
    else:
        print(a, end=" ")
        print(b)
 
# Driver Code
if __name__ == "__main__":
    K = 5
    findPrimeNumbers(K)
     
    # This code is contributed by rakeshsahni


C#
// C# program for the above approach
using System;
 
class GFG {
 
    // Function to find two consecutive
    // perfect square numbers whose
    // difference is N
    static void findPrimeNumbers(int N)
    {
        int a, b;
        a = (N / 2) * (N / 2);
        b = ((N + 1) / 2) * ((N + 1) / 2);
 
        if ((N % 2) == 0)
            Console.WriteLine("-1");
        else
            Console.WriteLine(a + " " + b);
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        int K = 5;
        findPrimeNumbers(K);
    }
}
 
// This code is contributed by ukasp.


Javascript


输出:
4 9

时间复杂度: O(1)
辅助空间: O(1)