Let be the number of cats and is the number of dogs. As we’ve to distribute chocolates and cakes equally, and must be divisor of and the duration is . So, find all the divisors of which are greater than . Then, for each divisor, find the minimum divisor by a binary search for which the multiple of them will be equal or greater than . Overall time complexity where is the number of divisors.