Check if A can be converted to B by reducing with a Prime number
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.
Input: A = 10, B = 4
Let P = 2 and after subtracting it
three times from A
Input: A = 41, B = 40
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
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: