![]() |
VOOZH | about |
Given a range from L to R and every Xth tile is painted black and every Yth tile is painted white in that range from L to R. If a tile is painted both white and black, then it is considered to be painted grey. The task is to find the number of tiles that are colored grey in range L to R (both inclusive).
Examples:
Input: X = 2, Y = 3, L = 6, R = 18 Output: 3 The grey coloured tiles are numbered 6, 12, 18 Input: X = 1, Y = 4, L = 5, R = 10 Output: 1 The only grey coloured tile is 8.
Approach: Since every multiple of X is black and every multiple of Y is white. Any tile which is a multiple of both X and Y would be grey. The terms that are divisible by both X and Y are the terms that are divisible by the lcm of X and Y.
Lcm can be found out using the following formula:
lcm = (x*y) / gcd(x, y)
GCD can be computed in logn time using Euclid's algorithm. The number of multiples of lcm in range L to R can be found by using a common trick of:
count(L, R) = count(R) - count(L-1)
Number of terms divisible by K less than N is:
floor(N/K)
Below is the implementation to find the number of grey tiles:
3
Time Complexity: O(log(min(x, y))), where x and y are two parameters of gcd.