Check if A can be converted to B by reducing with a Prime number
Last Updated :
22 Feb, 2023
Given two integers, A and B, the task is to find whether it is possible to make A equal to B if you are allowed to subtract a prime number P any number of times from A.
Examples:
Input: A = 10, B = 4
Output: YES
Explanation:
Let P = 2 and after subtracting it
three times from A
Input: A = 41, B = 40
Output: NO
Approach: The key observation in the problem is we have to represent the number A as
, As we know every number is divisible by some prime number except 1. Therefore if we find the difference of the number
and if the difference is greater than 1 then both the number can be made equal by subtracting a prime number X times from A.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool isPossible( int A, int B)
{
return (A - B > 1);
}
int main()
{
int A = 10, B = 4;
if (isPossible(A, B))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
class GFG{
static boolean isPossible( int A, int B)
{
return (A - B > 1 );
}
public static void main (String[] args)
{
int A = 10 , B = 4 ;
if (isPossible(A, B))
System.out.print( "Yes" );
else
System.out.print( "No" );
}
}
|
Python3
def isPossible(A, B):
return (A - B > 1 );
A = 10 ; B = 4 ;
if (isPossible(A, B)):
print ( "Yes" );
else :
print ( "No" );
|
C#
using System;
class GFG{
static bool isPossible( int A, int B)
{
return (A - B > 1);
}
public static void Main()
{
int A = 10, B = 4;
if (isPossible(A, B))
Console.Write( "Yes" );
else
Console.Write( "No" );
}
}
|
Javascript
<script>
function isPossible(A, B)
{
return (A - B > 1);
}
let A = 10, B = 4;
if (isPossible(A, B))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Output:
Yes
Time Complexity: O(1).
Space Complexity: O(1) as no extra space has been used.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...