Given two integers X and Y where X > Y, the task is to check if there exists an prime number P such that if P is repeatedly subtracted from X then it gives Y.
Input: X = 100, Y = 98
(100 – (2 * 1) = 98)
Input: X = 45, Y = 31
(45 – (7 * 2)) = 31
Naive approach: Run a loop for every integer starting from 2 to x. If the 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 a 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:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.