Check if there exists a prime number which gives Y after being repeatedly subtracted from X
Last Updated :
03 Mar, 2022
Given two integers X and Y where X > Y, the task is to check if there exists a prime number P such that if P is repeatedly subtracted from X then it gives Y.
Examples:
Input: X = 100, Y = 98
Output: Yes
(100 – (2 * 1) = 98)
Input: X = 45, Y = 31
Output: Yes
(45 – (7 * 2)) = 31
Naive approach: Run a loop for every integer starting from 2 to x. If a current number is a prime number, and it meets the criteria given in the question, then it is the required number.
Efficient approach: Notice that for a valid prime p, x – k * p = y or x – y = k * p. Suppose, p = 2 then (x – y) = 2, 4, 6, … (all even numbers). This means if (x – y) is even then the answer is always true. If (x – y) is an odd number other than 1, it will always have a prime factor. Either it itself is prime or it is a product of a smaller prime and some other integers. So the answer is True for all odd numbers other than 1.
What if (x – y) = 1, it is neither a prime nor composite. So this is the only case where the answer is false.
Below is the implementation of the approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool isPossible( int x, int y)
{
if ((x - y) == 1)
return false ;
return true ;
}
int main()
{
int x = 100, y = 98;
if (isPossible(x, y))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
import java.util.*;
class GFG
{
static boolean isPossible( int x, int y)
{
if ((x - y) == 1 )
return false ;
return true ;
}
public static void main(String[] args)
{
int x = 100 , y = 98 ;
if (isPossible(x, y))
System.out.print( "Yes" );
else
System.out.print( "No" );
}
}
|
Python3
def isPossible(x, y):
if ((x - y) = = 1 ):
return False
return True
x = 100
y = 98
if (isPossible(x, y)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG
{
static bool isPossible( int x, int y)
{
if ((x - y) == 1)
return false ;
return true ;
}
public static void Main(String[] args)
{
int x = 100, y = 98;
if (isPossible(x, y))
Console.Write( "Yes" );
else
Console.Write( "No" );
}
}
|
Javascript
<script>
function isPossible(x , y) {
if ((x - y) == 1)
return false ;
return true ;
}
var x = 100, y = 98;
if (isPossible(x, y))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...