Given two numbers n
and m
, find the n-th root of m
. In mathematics, the n-th root of a number m
is a real number that, when raised to the power of n
, gives m
. If no such real number exists, return -1.
Examples:
Input: n = 2, m = 9
Output: 3
Explanation: 32 = 9
Input: n = 3, m = 9
Output: -1
Explanation: 3rd root of 9 is not integer.
Approach - Using Binary Search
The approach uses binary search to find the n-th root of a number m. The search range is between 1 and m, and in each iteration, the middle value mid is raised to the power of n.
- If mid^n equals m, mid is the root.
- If mid^n is greater than m, the search range is narrowed to smaller values, and
- if mid^n is smaller than m, the search range is adjusted to larger values.
- The process continues until the root is found or the range is exhausted. If no exact root is found, the result is -1
C++
#include <iostream>
using namespace std;
int nthRoot(int n, int m) {
if (n == 1) {
return m;
}
long long int low = 1LL, high = m, mid;
long long int ans = -1;
while (low <= high) {
mid = (low + high) / 2;
long long int x = mid;
for (int i = 1; i < n; i++) {
x *= mid;
if (x > m * 1LL)
break;
}
if (x == m * 1LL) {
ans = mid;
break;
} else if (x > m)
high = mid - 1;
else
low = mid + 1;
}
return int(ans);
}
int main() {
int n = 1, m = 14;
int result = nthRoot(n, m);
cout << result << endl;
return 0;
}
C
#include <stdio.h>
int nthRoot(int n, int m) {
if (n == 1) {
return m;
}
long long int low = 1LL, high = m, mid;
long long int ans = -1;
while (low <= high) {
mid = (low + high) / 2;
long long int x = mid;
for (int i = 1; i < n; i++) {
x *= mid;
if (x > m * 1LL)
break;
}
if (x == m * 1LL) {
ans = mid;
break;
} else if (x > m)
high = mid - 1;
else
low = mid + 1;
}
return (int)ans;
}
int main() {
int n = 1, m = 14;
int result = nthRoot(n, m);
printf("%d\n", result);
return 0;
}
Java
public class GfG {
public static int nthRoot(int n, int m) {
if (n == 1) {
return m;
}
long low = 1, high = m, mid;
long ans = -1;
while (low <= high) {
mid = (low + high) / 2;
long x = mid;
for (int i = 1; i < n; i++) {
x *= mid;
if (x > m)
break;
}
if (x == m) {
ans = mid;
break;
} else if (x > m)
high = mid - 1;
else
low = mid + 1;
}
return (int)ans;
}
public static void main(String[] args) {
int n = 1, m = 14;
int result = nthRoot(n, m);
System.out.println(result);
}
}
Python
def nthRoot(n, m):
if n == 1:
return m
low, high = 1, m
ans = -1
while low <= high:
mid = (low + high) // 2
x = mid
for i in range(1, n):
x *= mid
if x > m:
break
if x == m:
ans = mid
break
elif x > m:
high = mid - 1
else:
low = mid + 1
return int(ans)
n = 1
m = 14
result = nthRoot(n, m)
print(result)
C#
using System;
class GfG{
static int NthRoot(int n, int m) {
if (n == 1) {
return m;
}
long low = 1, high = m, mid;
long ans = -1;
while (low <= high) {
mid = (low + high) / 2;
long x = mid;
for (int i = 1; i < n; i++) {
x *= mid;
if (x > m)
break;
}
if (x == m) {
ans = mid;
break;
} else if (x > m)
high = mid - 1;
else
low = mid + 1;
}
return (int)ans;
}
static void Main() {
int n = 1, m = 14;
int result = NthRoot(n, m);
Console.WriteLine(result);
}
}
JavaScript
function nthRoot(n, m) {
if (n === 1) {
return m;
}
let low = 1, high = m, mid;
let ans = -1;
while (low <= high) {
mid = Math.floor((low + high) / 2);
let x = mid;
for (let i = 1; i < n; i++) {
x *= mid;
if (x > m) break;
}
if (x === m) {
ans = mid;
break;
} else if (x > m)
high = mid - 1;
else
low = mid + 1;
}
return ans;
}
const n = 1, m = 14;
const result = nthRoot(n, m);
console.log(result);
Time Complexity: O(n*log m)
Auxiliary Space: O(1)
Approach - Using Newton's Method
This problem involves finding the real-valued function A^{1/N}, 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:
\frac{f(x_k)}{f'(x_k)}
Here, we define the function f(x) as:
f(x) = xN- A
The derivative of f(x), denoted f'(x), is:
N\cdot x^{N - 1}
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:
\frac{1}{N} \left( (N - 1) \cdot x_k + \frac{A}{x_k^{N - 1}} \right)
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.
C++
#include <bits/stdc++.h>
using namespace std;
int nthRoot(int m, int n)
{
if (n == 1) {
return m;
}
double xPre = rand() % 10 + 1;
// Smaller eps denotes more accuracy
double eps = 1e-3;
// Initializing difference between two roots
double delX = INT_MAX;
// xK denotes current value of x
double xK;
// Loop until we reach the desired accuracy
while (delX > eps)
{
// Calculating the current value from the previous value by Newton's method
xK = ((n - 1.0) * xPre + (double)m / pow(xPre, n - 1)) / (double)n;
delX = abs(xK - xPre);
xPre = xK;
}
return (int)round(xK);
}
int main() {
int n = 1, m = 14;
int nthRootValue = nthRoot(m, n);
cout << nthRootValue << endl;
return 0;
}
C
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <limits.h>
int nthRoot(int m, int n) {
if (n == 1) {
return m;
}
double xPre = rand() % 10 + 1;
// Smaller eps denotes more accuracy
double eps = 1e-3;
// Initializing difference between two roots
double delX = 1e6;
// xK denotes current value of x
double xK;
// Loop until we reach the desired accuracy
while (delX > eps) {
// Calculating the current value from the previous value by Newton's method
xK = ((n - 1.0) * xPre + (double)m / pow(xPre, n - 1)) / (double)n;
delX = fabs(xK - xPre);
xPre = xK;
}
return (int)round(xK);
}
int main() {
int n = 1, m = 14;
int nthRootValue = nthRoot(m, n);
printf("%d\n", nthRootValue);
return 0;
}
Java
import java.lang.Math;
import java.util.Random;
public class GfG {
public static int nthRoot(int m, int n) {
if (n == 1) {
return m;
}
Random rand = new Random();
// Initial guess (use m / 2 or another logic to get a reasonable starting point)
double xPre = rand.nextInt(10) + 1;
// Smaller eps denotes more accuracy
double eps = 1e-3;
// Initializing difference between two roots
double delX = Double.MAX_VALUE;
// xK denotes current value of x
double xK = xPre;
// Loop until we reach the desired accuracy
while (delX > eps) {
// Calculating the current value from the previous value by Newton's method
xK = ((n - 1.0) * xPre + (double)m / Math.pow(xPre, n - 1)) / (double)n;
delX = Math.abs(xK - xPre);
xPre = xK;
}
return (int)Math.round(xK);
}
public static void main(String[] args) {
int n = 1, m = 14;
int nthRootValue = nthRoot(m, n);
System.out.println(nthRootValue);
}
}
Python
import random
import math
def nthRoot(m, n):
if n == 1:
return m
xPre = random.randint(1, 10)
# Smaller eps denotes more accuracy
eps = 1e-3
# Initializing difference between two roots
delX = float('inf')
# xK denotes current value of x
xK = 0.0
# Loop until we reach the desired accuracy
while delX > eps:
# Calculating the current value from the previous value by Newton's method
xK = ((n - 1.0) * xPre + m / (xPre ** (n - 1))) / n
delX = abs(xK - xPre)
xPre = xK
return round(xK)
if __name__ == '__main__':
n = 1
m = 14
nthRootValue = nthRoot(m, n)
print(nthRootValue)
C#
using System;
class GfG {
public static int nthRoot(int m, int n) {
if (n == 1) {
return m;
}
Random rand = new Random();
double xPre = rand.Next(1, 11);
// Smaller eps denotes more accuracy
double eps = 1e-3;
// Initializing difference between two roots
double delX = double.MaxValue;
// xK denotes current value of x, initialize with xPre
double xK = xPre;
// Loop until we reach the desired accuracy
while (delX > eps) {
// Calculating the current value from the previous value by Newton's method
xK = ((n - 1.0) * xPre + (double)m / Math.Pow(xPre, n - 1)) / (double)n;
delX = Math.Abs(xK - xPre);
xPre = xK;
}
// Return the integer part of the result (rounded to nearest integer)
return (int)Math.Round(xK);
}
// Driver code to test the nthRoot method
public static void Main() {
int n = 1, m = 14;
int nthRootValue = nthRoot(m, n);
Console.WriteLine(nthRootValue);
}
}
JavaScript
function nthRoot(m, n) {
if (n === 1) {
return m;
}
let xPre = Math.floor(Math.random() * 10) + 1;
// Smaller eps denotes more accuracy
const eps = 1e-3;
// Initializing difference between two roots
let delX = Infinity;
// xK denotes current value of x
let xK;
// Loop until we reach the desired accuracy
while (delX > eps) {
// Calculating the current value from the previous value by Newton's method
xK = ((n - 1) * xPre + m / Math.pow(xPre, n - 1)) / n;
delX = Math.abs(xK - xPre);
xPre = xK;
}
// Return the integer part of the result
return Math.round(xK);
}
const n = 1, m = 14;
const nthRootValue = nthRoot(m, n);
console.log(nthRootValue);
Time Complexity: O(log(eps)), where eps is the desired accuracy.
Space Complexity: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem