给定数字N ,任务是检查此数字是否可以表示为两个完美平方的差。
例子:
Input: N = 3
Output: Yes
Explanation:
22 – 11 = 3
Input: N = 10
Output: No
方法:这个想法是所有的数字都可以表示为两个平方的差,除了当除以4时得出2的余数的数字。
让我们通过一些示例来形象地看待这一点:
N = 4 => 42 - 02
N = 6 => Can't be expressed as 6 % 4 = 2
N = 8 => 32 - 12
N = 10 => Can't be expressed as 10 % 4 = 2
N = 11 => 62 - 52
N = 12 => 42 - 22
and so on...
因此,想法是在给定数字除以4时简单地检查2的余数。
下面是上述方法的实现:
C++
// C++ program to check whether a number
// can be represented by the difference
// of two squares
#include
using namespace std;
// Function to check whether a number
// can be represented by the difference
// of two squares
bool difSquare(int n)
{
// Checking if n % 4 = 2 or not
if (n % 4 != 2) {
return true;
}
return false;
}
// Driver code
int main()
{
int n = 45;
if (difSquare(n)) {
cout << "Yes\n";
}
else {
cout << "No\n";
}
return 0;
}
Java
// Java program to check whether a number
// can be represented by the difference
// of two squares
import java.util.*;
class GFG{
// Function to check whether a number
// can be represented by the difference
// of two squares
static boolean difSquare(int n)
{
// Checking if n % 4 = 2 or not
if (n % 4 != 2)
{
return true;
}
return false;
}
// Driver code
public static void main(String[] args)
{
int n = 45;
if (difSquare(n))
{
System.out.print("Yes\n");
}
else
{
System.out.print("No\n");
}
}
}
// This code is contributed by shivanisinghss2110
Python3
# Python3 program to check whether a number
# can be represented by the difference
# of two squares
# Function to check whether a number
# can be represented by the difference
# of two squares
def difSquare(n):
# Checking if n % 4 = 2 or not
if (n % 4 != 2):
return True
return False
# Driver code
if __name__ == '__main__':
n = 45
if (difSquare(n)):
print("Yes")
else:
print("No")
# This code is contributed by mohit kumar 29
C#
// C# program to check whether a number
// can be represented by the difference
// of two squares
using System;
class GFG{
// Function to check whether a number
// can be represented by the difference
// of two squares
static bool difSquare(int n)
{
// Checking if n % 4 = 2 or not
if (n % 4 != 2)
{
return true;
}
return false;
}
// Driver code
public static void Main()
{
int n = 45;
if (difSquare(n))
{
Console.Write("Yes\n");
}
else
{
Console.Write("No\n");
}
}
}
// This code is contributed by Nidhi_biet
Javascript
输出:
Yes