Given a number n. Find positive numbers a(0 < a <= 109) and b(0 < b <= 109) such that they satisfy the equation log2a + log3b = n. Return any possible integer array of a and b, if the equation can be satisfied otherwise return the single integer array containing -1 which means there is no such a and b exists. Solution will be accepted if |n-log2a + log3b| < 10-6.
Examples:
Input: 3
Output: [1, 27]
Explanation: log2(1) = 0 and log3(27) = 3, 0 + 3 = 3 or [4, 3], [2, 9],...also can be the possible answer.
Input: 40
Output: [4194304, 387420489]
Approach: To solve the problem follow the below steps:
- If we see the a's and b's range it is upto 109. So, we try to loop through all possibilities using two for loops but we get the time limit exceeds. That's why the intuition here is to reduce the search for a and b.
- So, if we do log2(109) ~ 29 and log3(109) ~ 18. Here we took the integer part.
- Therefore, if n = a + b = 29 + 18 = 47 is the maximum value.
- Here in this code, we check that if n > 47 then we return -1 to indicate that there is no such a and b exists.
- Then the nested loop explores all the possible values of a and b such that t 2i + 3j = n.
- Then the code will calculate log(2, a) + log(3,b) to check that the value is approximately n with a small epsilon.
- If the calculated value is within the epsilon range then return the result.
- If the loops are complete without finding a valid solution, the code returns [-1] to indicate that no 'a' and 'b' were found for the given 'n'.
- The use of epsilon for comparison addresses the precision limitations of floating-point calculations.
Below is the implementation of the approach.
Time Complexity: O(19*30) = O(570) = O(1)
Auxiliary Space: O(1)