Given three integers x, y, z, the task is to find the largest non-negative number less than or equal to z that leaves a remainder x when divided by y (Given x < y). If no such number exists then the output will be -1.
Input: x = 1, y = 5, z = 8 Output: 6 Explanation: 6 is the largest number less than 8 which when divided by 5 leaves a remainder 1. Input: x = 4, y = 6, z = 3 Output: -1 Explanation: Since no such number exists the output is -1
Approach: To solve the problem mentioned above the very first observation is if x > z then answer will not be possible, so output will be -1.
Let the required number be p. Following are the two equations for solving the problem:
- p * y + x = 0
- p * y <= (z – x)
In order to find the answer, we need to find the value of p. So,
p = (z - x) / y
After calculating p we can simply find the answer which is
p * y + x
Below is the implementation of the above approach:
Time Complexity: O(1 )
Auxiliary Space: O(1)
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.