Given three positive integers a, b and n, our task is to find the total count of all the numbers K ranging from 0 to n which satisfies the given equation (( k % a ) % b) = (( k % b ) % a)
Input: a = 3, b = 4, n = 25
The values which satisfies the above equation are 0 1 2 3 12 13 14 15 24 25. For example, for K = 13; ((13 % 3) % 4) gives 1 and ((13 % 4) % 3) also gives 1 as output.
Input: a = 1, b = 13, n = 500
In total there are 501 numbers between 0 and 500 which satisfies the given equation.
To solve the problem mentioned above we have the given condition (( k % a ) % b) = (( k % b ) % a) which will always be satisfied for numbers from 0 to max(a, b) – 1. So according to the statement provided above if we have a <= b then check all number from 0 to b-1 and we have the following two cases:
- We calculate (k % a) % b, in this case answer will always be (k % a) since the value of (k % a) will always be less than b.
- We calculate (k % b) % a, in this case also answer will always be (k % a) because (k % b) will return k as k is less than b.
Similarly, we can check the cases for a > b. So now we need to check all numbers which are divisible by both a and b in the range 0 to n. This can be found with the help of LCM of a and b. So, now we can easily find the number of multiples of the LCM in the range 0 to n by diving n by LCM. We will add 1 to the multiples to include 0 as a multiple. And then we have to multiply the number of multiples by max(a, b) so that we can find all numbers which satisfy the given condition. But if the sum of the last multiple and max(a, b) exceeds our range of n numbers then we need to exclude the extra numbers.
Below is the implementation of the above 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.