VOOZH about

URL: https://www.geeksforgeeks.org/dsa/n-th-root-number/

⇱ N-th root of a number - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

N-th root of a number

Last Updated : 28 Mar, 2026

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 = 27

Input: n = 3, m = 9
Output: -1
Explanation: 3rd root of 9 is not integer.

[Approach 1] Using Binary Search - O(n * log(m)) Time and O(1) Space

The idea is to search within the range from 1 to m. In each step, we do the following

  • The middle value is raised to the power of n and compared to m. If it equals m, that value is the root.
  • If it is greater, the search continues in the lower half; if smaller, in the upper half.

This process repeats until the root is found or the range is exhausted. If no exact integer root exists, the function returns -1.


Output
3

[Approach 2] Using Newton's Method

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.


Output
3

Time Complexity: O(log(eps)), where eps is the desired accuracy.
Space Complexity: O(1)

Comment