You are given two positive integers 'n' and 'm'. You have to return the 'nth' root of 'm', i.e. 'm(1/n)'. If the 'nth root is not an integer, return -1.
'nth' root of an integer 'm' is a number, which, when raised to the power 'n', gives 'm' as a result.
Input: ‘n’ = 3, ‘m’ = 27
Output: 3
Explanation:
3rd Root of 27 is 3, as (3)^3 equals 27.
The first line of the input consists of two space-separated integers, n and m.
Return an integer that denotes the nth root of m in a separate line. If such an integer doesn't exist return -1.
You don't have to print anything. It has already been taken care of. Just Implement the given function.
3 27
3
3rd Root of 27 is 3, as (3)^3 equals 27.
4 69
-1
4th Root of 69 is not an integer, hence -1.
Try to do this in O(log(n+m)).
1 <= n <= 30
1 <= m <= 10^9
Time Limit: 1 sec.
Is there any monotonic function followed for this problem?
The idea for this approach is to use binary search to find an integer equal to ‘M’ when multiplied by itself ‘N’ times.
The exponential function is an increasing function (i.e., monotonic), and thus, using binary search, we will try out different possible square roots; let’s suppose we are currently on ‘X’, then we will find
To find the value of ‘XN’, we can use a loop, which will iterate ‘N’ times.
The steps are as follows:-
// Function to find the Nth root of M
function NthRoot(int n, int m):
O( n * log(M) ), Where ‘N’ and ‘M’ are input integers.
In the above algorithm, the search space is ‘M’, and hence in ‘log(M)’ iterations, we will find the ‘N’th root, and in each iteration, we find the ‘N’th power of ‘mid’ using a loop.
Hence the time complexity will be O( n * log(M) )
O( 1 ).
In the above algorithm, we only use variables.
Hence the space complexity will be O( 1 ).