![]() |
VOOZH | about |
Given two integers n and m, find the n-th root of m. The n-th root of m is an integer x such that x^n = m. If no such integer exists, return -1.
Examples:
Input: n = 3, m = 27
Output: 3
Explanation: 33 = 27Input: n = 3, m = 9
Output: -1
Explanation: 3rd root of 9 is not integer.
Table of Content
The idea is to search within the range from 1 to m. In each step, we do the following
This process repeats until the root is found or the range is exhausted. If no exact integer root exists, the function returns -1.
3
This problem involves finding the real-valued function , which can be solved using Newton's method. The method begins with an initial guess and iteratively refines the result.
By applying Newton's method, we derive a relation between consecutive iterations:
According to Newton's method:
Here, we define the function f(x) as:
f(x) = xN- A
The derivative of f(x), denoted f'(x), is:
The value xk represents the approximation at the k-th iteration. By substituting f(x) and f'(x) into the Newton's method formula, we obtain the following update relation:
Using this relation, the problem can be solved by iterating over successive values of x until the difference between consecutive iterations is smaller than the desired accuracy.
Note: The code below returns the approx value so we use the check to find the if the real nth root is exact.
3
Time Complexity: O(log(eps)), where eps is the desired accuracy.
Space Complexity: O(1)