📜  检查是否存在素数,该素数在从X重复减去后得到Y

📅  最后修改于: 2021-05-06 07:22:49             🧑  作者: Mango

给定两个整数XY ,其中X> Y ,任务是检查是否存在质数P ,使得如果从X重复减去P则得出Y。

例子:

天真的方法:对从2x的每个整数运行一个循环。如果当前数字是质数,并且满足问题中给出的条件,则它是必需的数字。

有效方法:请注意,对于有效质数px – k * p = yx – y = k * p 。假设p = 2,(x – y)= 2,4,6,… (所有偶数)。这意味着,如果(x – y)是偶数,则答案始终是正确的。如果(X – Y)是除1以外的奇数,它总是有一个主要因素。它本身就是素数,或者是较小素数和其他一些整数的乘积。因此,对于除1以外的所有奇数,答案为True。
如果(x – y)= 1怎么办,它既不是素数也不是合成数。因此,这是答案为假的唯一情况。

下面是该方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
  
// Function that returns true if any
// prime number satisfies
// the given conditions
bool isPossible(int x, int y)
{
  
    // No such prime exists
    if ((x - y) == 1)
        return false;
  
    return true;
}
  
// Driver code
int main()
{
    int x = 100, y = 98;
  
    if (isPossible(x, y))
        cout << "Yes";
    else
        cout << "No";
  
    return 0;
}


Java
// Java implementation of the approach
import java.util.*;
  
class GFG
{
  
// Function that returns true if any
// prime number satisfies
// the given conditions
static boolean isPossible(int x, int y)
{
  
    // No such prime exists
    if ((x - y) == 1)
        return false;
  
    return true;
}
  
// Driver code
public static void main(String[] args)
{
    int x = 100, y = 98;
  
    if (isPossible(x, y))
        System.out.print("Yes");
    else
        System.out.print("No");
}
}
  
// This code is contributed by Rajput-Ji


Python3
# Python3 implementation of the approach
  
# Function that returns true if any
# prime number satisfies
# the given conditions
def isPossible(x, y):
  
    # No such prime exists
    if ((x - y) == 1):
        return False
  
    return True
  
# Driver code
x = 100
y = 98
  
if (isPossible(x, y)):
    print("Yes")
else:
    print("No")
  
# This code is contributed by Mohit Kumar


C#
// C# implementation of the approach
using System;
  
class GFG
{
  
// Function that returns true if any
// prime number satisfies
// the given conditions
static bool isPossible(int x, int y)
{
  
    // No such prime exists
    if ((x - y) == 1)
        return false;
  
    return true;
}
  
// Driver code
public static void Main(String[] args)
{
    int x = 100, y = 98;
  
    if (isPossible(x, y))
        Console.Write("Yes");
    else
        Console.Write("No");
}
}
  
// This code is contributed by 29AjayKumar


输出:
Yes