The Wayback Machine - https://web.archive.org/web/20241122182128/https://www.geeksforgeeks.org/n-th-root-number/
Open In App

N-th root of a number

Last Updated : 23 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given two numbers N and A, find N-th root of A. In mathematics, Nth root of a number A is a real number that gives A, when we raise it to integer power N. These roots are used in Number Theory and other advanced branches of mathematics. 
Refer Wiki page for more information. 
Examples: 

Input : A = 81
        N = 4
Output : 3 
3^4 = 81
Recommended Practice

As this problem involves a real valued function A^(1/N) we can solve this using Newton’s method, which starts with an initial guess and iteratively shift towards the result. 
We can derive a relation between two consecutive values of iteration using Newton’s method as follows, 

according to newton’s method
x(K+1) = x(K) – f(x) / f’(x)        
here    f(x)  = x^(N) – A
so    f’(x) = N*x^(N - 1)
and     x(K) denoted the value of x at Kth iteration
putting the values and simplifying we get,
x(K + 1) = (1 / N) * ((N - 1) * x(K) + A / x(K) ^ (N - 1))

Using above relation, we can solve the given problem. In below code we iterate over values of x, until difference between two consecutive values of x become lower than desired accuracy.
Below is the implementation of above approach: 

C++




// C++ program to calculate Nth root of a number
#include <bits/stdc++.h>
using namespace std;
 
//  method returns Nth power of A
double nthRoot(int A, int N)
{
    // initially guessing a random number between
    // 0 and 9
    double xPre = rand() % 10;
 
    //  smaller eps, denotes more accuracy
    double eps = 1e-3;
 
    // initializing difference between two
    // roots by INT_MAX
    double delX = INT_MAX;
 
    //  xK denotes current value of x
    double xK;
 
    //  loop until we reach desired accuracy
    while (delX > eps)
    {
        //  calculating current value from previous
        // value by newton's method
        xK = ((N - 1.0) * xPre +
              (double)A/pow(xPre, N-1)) / (double)N;
        delX = abs(xK - xPre);
        xPre = xK;
    }
 
    return xK;
}
 
//    Driver code to test above methods
int main()
{
    int N = 4;
    int A = 81;
 
    double nthRootValue = nthRoot(A, N);
    cout << "Nth root is " << nthRootValue << endl;
 
    /*
        double Acalc = pow(nthRootValue, N);
        cout << "Error in difference of powers "
             << abs(A - Acalc) << endl;
    */
 
    return 0;
}


Java




// Java program to calculate Nth root of a number
class GFG
{
     
    // method returns Nth power of A
    static double nthRoot(int A, int N)
    {
         
        // initially guessing a random number between
        // 0 and 9
        double xPre = Math.random() % 10;
     
        // smaller eps, denotes more accuracy
        double eps = 0.001;
     
        // initializing difference between two
        // roots by INT_MAX
        double delX = 2147483647;
     
        // xK denotes current value of x
        double xK = 0.0;
     
        // loop until we reach desired accuracy
        while (delX > eps)
        {
            // calculating current value from previous
            // value by newton's method
            xK = ((N - 1.0) * xPre +
            (double)A / Math.pow(xPre, N - 1)) / (double)N;
            delX = Math.abs(xK - xPre);
            xPre = xK;
        }
     
        return xK;
    }
     
    // Driver code
    public static void main (String[] args)
    {
        int N = 4;
        int A = 81;
     
        double nthRootValue = nthRoot(A, N);
        System.out.println("Nth root is "
        + Math.round(nthRootValue*1000.0)/1000.0);
     
        /*
            double Acalc = pow(nthRootValue, N);
            cout << "Error in difference of powers "
                << abs(A - Acalc) << endl;
        */
    }
}
 
// This code is contributed by Anant Agarwal.


Python3




# Python3 program to calculate
# Nth root of a number
import math
import random
 
# method returns Nth power of A
def nthRoot(A,N):
 
    # initially guessing a random number between
    # 0 and 9
    xPre = random.randint(1,101) % 10
  
    #  smaller eps, denotes more accuracy
    eps = 0.001
  
    # initializing difference between two
    # roots by INT_MAX
    delX = 2147483647
  
    #  xK denotes current value of x
    xK=0.0
  
    #  loop until we reach desired accuracy
    while (delX > eps):
 
        # calculating current value from previous
        # value by newton's method
        xK = ((N - 1.0) * xPre +
              A/pow(xPre, N-1)) /N
        delX = abs(xK - xPre)
        xPre = xK;
         
    return xK
 
# Driver code
N = 4
A = 81
nthRootValue = nthRoot(A, N)
 
print("Nth root is ", nthRootValue)
 
## Acalc = pow(nthRootValue, N);
## print("Error in difference of powers ",
##             abs(A - Acalc))
 
# This code is contributed
# by Anant Agarwal.


C#




// C# program to calculate Nth root of a number
using System;
class GFG
{
     
    // method returns Nth power of A
    static double nthRoot(int A, int N)
    {
        Random rand = new Random();
        // initially guessing a random number between
        // 0 and 9
        double xPre = rand.Next(10);;
     
        // smaller eps, denotes more accuracy
        double eps = 0.001;
     
        // initializing difference between two
        // roots by INT_MAX
        double delX = 2147483647;
     
        // xK denotes current value of x
        double xK = 0.0;
     
        // loop until we reach desired accuracy
        while (delX > eps)
        {
            // calculating current value from previous
            // value by newton's method
            xK = ((N - 1.0) * xPre +
            (double)A / Math.Pow(xPre, N - 1)) / (double)N;
            delX = Math.Abs(xK - xPre);
            xPre = xK;
        }
     
        return xK;
    }
     
    // Driver code
    static void Main()
    {
        int N = 4;
        int A = 81;
     
        double nthRootValue = nthRoot(A, N);
        Console.WriteLine("Nth root is "+Math.Round(nthRootValue*1000.0)/1000.0);
    }
}
 
// This code is contributed by mits


PHP




<?php
// PHP program to calculate
// Nth root of a number
 
// method returns
// Nth power of A
function nthRoot($A, $N)
{
    // initially guessing a
    // random number between
    // 0 and 9
    $xPre = rand() % 10;
 
    // smaller eps, denotes
    // more accuracy
    $eps = 0.001;
 
    // initializing difference
    // between two roots by INT_MAX
    $delX = PHP_INT_MAX;
 
    // xK denotes current
    // value of x
    $xK;
 
    // loop until we reach
    // desired accuracy
    while ($delX > $eps)
    {
        // calculating current
        // value from previous
        // value by newton's method
        $xK = ((int)($N - 1.0) *
                     $xPre + $A /
                     (int)pow($xPre,
                              $N - 1)) / $N;
        $delX = abs($xK - $xPre);
        $xPre = $xK;
    }
 
    return floor($xK);
}
 
// Driver code
$N = 4;
$A = 81;
 
$nthRootValue = nthRoot($A, $N);
echo "Nth root is " ,
      $nthRootValue ,"\n";
 
// This code is contributed by akt_mit
?>


Javascript




<script>
 
// Javascript program for the above approach
   
    // method returns Nth power of A
    function nthRoot(A, N)
    {
           
        // initially guessing a random number between
        // 0 and 9
        let xPre = Math.random() % 10;
       
        // smaller eps, denotes more accuracy
        let eps = 0.001;
       
        // initializing difference between two
        // roots by INT_MAX
        let delX = 2147483647;
       
        // xK denotes current value of x
        let xK = 0.0;
       
        // loop until we reach desired accuracy
        while (delX > eps)
        {
            // calculating current value from previous
            // value by newton's method
            xK = ((N - 1.0) * xPre +
            A / Math.pow(xPre, N - 1)) / N;
            delX = Math.abs(xK - xPre);
            xPre = xK;
        }
       
        return xK;
    }
        
 
// Driver Code
     
        let N = 4;
        let A = 81;
       
        let nthRootValue = nthRoot(A, N);
        document.write("Nth root is "+Math.round(nthRootValue*1000.0)/1000.0);
         
</script>


Output

Nth root is 3

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

 



Previous Article
Next Article

Similar Reads

Smallest root of the equation x^2 + s(x)*x - n = 0, where s(x) is the sum of digits of root x.
You are given an integer n, find the smallest positive integer root of equation x, or else print -1 if no roots are found.Equation: x^2 + s(x)*x - n = 0where x, n are positive integers, s(x) is the function, equal to the sum of digits of number x in the decimal number system. 1 <= N <= 10^18 Examples: Input: N = 110 Output: 10 Explanation: x
8 min read
Digital Root (repeated digital sum) of square of an integer using Digital root of the given integer
Given an integer N, the task is to find the digital root N2 using the digital root of N. Digital Root of a positive integer is calculated by adding the digits of the integer. If the resultant value is a single digit, then that digit is the digital root. If the resultant value contains two or more digits, those digits are summed and the process is r
6 min read
Find if there is a pair in root to a leaf path with sum equals to root's data
Given a binary tree, find if there is a pair in root to a leaf path such that sum of values in pair is equal to root's data. For example, in below tree there are no pairs in any root to leaf path with sum equal to root's data. The idea is based on hashing and tree traversal. The idea is similar to method 2 of array pair sum problem. Create an empty
8 min read
Why do we check up to the square root of a number to determine if that number is Prime?
Why do we check up to the square root of a number to determine if that number is prime?Prime numbers are natural numbers greater than 1 which are divisible only by 1 and itself. Examples include 2, 3, 5, 7, 11, 13, etc. (1 is neither prime nor composite). Here is the code to check whether a number is prime or not. As, the loop checks for each numbe
3 min read
Number of elements smaller than root using preorder traversal of a BST
Given a preorder traversal of a BST. The task is to find the number of elements less than root. Examples: Input: preorder[] = {3, 2, 1, 0, 5, 4, 6} Output: 3 Input: preorder[] = {5, 4, 3, 2, 1} Output: 4 For a binary search tree, a preorder traversal is of the form: root, { elements in left subtree of root }, { elements in right subtree of root } S
9 min read
Root to leaf path sum equal to a given number in BST
Given a BST and a number. The task is to check whether the given number is equal to the sum of all the node from root leaf across any of the root to leaf paths in the given Binary Search Tree. Approach: The idea is to traverse from root to all leaves in top-down fashion maintaining a path[] array to store current root to leaf path. While traversing
8 min read
Print a number containing K digits with digital root D
Given a digital root 'D' and number of digits 'K'. The task is to print a number containing K digits that has its digital root equal to D. Print '-1' if such a number does not exist. Examples: Input: D = 4, K = 4 Output: 4000 No. of digits is 4. Sum of digits is also 4. Input: D = 0, K = 1 Output: 0 Approach: A key observation to solving this probl
4 min read
Root to leaf path product equal to a given number
Given a binary tree and a number, the return is true if the tree has a root-to-leaf path such that the product of all the values along that path equals the given number. The return is false if no such path can be found. For example, in the above tree, there exist three roots to leaf paths with the following products. 240 –> 10 – 8 – 3400 –> 1
9 min read
Shortest root to leaf path sum equal to a given number
Given a binary tree and a number, the task is to return the length of the shortest path beginning at the root and ending at a leaf node such that the sum of numbers along that path is equal to ‘sum’. Print "-1" if no such path exists. Examples: Input: 1 / \ 10 15 / \ 5 2 Number = 16 Output: 2 There are two paths: 1->15, length of path is 3 1-
9 min read
Square root of a number without using sqrt() function
Given a number N, the task is to find the square root of N without using sqrt() function. Examples: Input: N = 25 Output: 5 Input: N = 3 Output: 1.73205 Input: N = 2.5 Output: 1.58114 Approach 1: We can consider (?x-?x)2 = 0.Replacing one of the ?x's with y, then the equation becomes (y-?x)2 => y2 - 2y?x + x = 0=> ?x = (y2 + x) / 2y=> ?x =
14 min read
Digital Root of a given large number using Recursion
Given a large number num in the form of string with length as N, the task is to find its digital root. The digital root of a positive integer is found by summing the digits of the integer. If the resulting value is a single digit then that digit is the digital root. If the resulting value contains two or more digits, those digits are summed and the
7 min read
Count the number of paths from root to leaf of a Binary tree with given XOR value
Given a value K and a binary tree, we have to find out the total number of paths from the root to leaf nodes having XOR of all its nodes along the path equal to K.Examples: Input: K = 6 2 / \ 1 4 / \ 10 5 Output: 2 Explanation: Subtree 1: 2 \ 4 This particular path has 2 nodes, 2 and 4 and (2 xor 4) = 6. Subtree 2: 2 / 1 \ 5 This particular path ha
8 min read
Maximize the number of uncolored vertices appearing along the path from root vertex and the colored vertices
Given a tree with N vertices numbered 1 through N with vertex 1 as root vertex and N - 1 edges. We have to color exactly k number of vertices and count the number of uncolored vertices between root vertex and every colored vertex. We have to include the root vertex in the count if it is not colored. The task to maximize the number of uncolored vert
8 min read
Find Cube root of a number using Log function
Given the number N, the task is to find the cube root using the log function.Examples: Input: N = 8 Output: 2.000000Input: N = 27 Output: 3.000000 Approach: To solve the problem mentioned above we will use log() function, according to the following formula: Let cube root of N be d. => ?N = d => N(1/3) = d Now, apply log on both sides: log3 (N
3 min read
Nth root of a number using log
Given two integers N and K, the task is to find the Nth root of the K. Examples: Input: N = 3, K = 8 Output: 2.00 Explanation: Cube root of 8 is 2. i.e. 23 = 8 Input: N = 2, K = 16 Output: 4.00 Explanation: Square root of 16 is 4, i.e. 42 = 16 Approach: The idea is to use logarithmic function to find the Nth root of K. Let D be our Nth root of the
3 min read
Min operations to reduce N by multiplying by any number or taking square root
Given a number N, the task is to find the minimum value of N by applying below operations any number of times: Multiply N by any positive integerReplace N with sqrt(N), only if N is a perfect square. Examples: Input: N = 20 Output: 10Explanation: Multiply -> 20 * 5 = 100 sqrt(100) = 10, which is the minimum value obtainable. Input: N = 5184 Outp
4 min read
Find square root of a number using Bit Manipulation
Given a non-negative integer N, the task is to find the square root of N using bitwise operations. If the integer is not the perfect square, return largest integer that is smaller than or equal to square root of N i.e., floor(√N). Examples: Input: N = 36Output: 6Explanation: The square root of 36 is 6. Input: N = 19Output: 4Explanation: The square
7 min read
Count numbers in range [L, R] that are divisible by square root of a number
Given two numbers L and R, the task is to find the count of all numbers in a given range [L, R] that are divisible by the square root of that number. The square root of a number is the value that, when multiplied by itself, gives the original number. Note: Here square root of a number represents the floor division. i.e, sqrt(4) = 2, sqrt(10) = 3, s
9 min read
Find root of a number using Newton's method
Given an integer N and a tolerance level L, the task is to find the square root of that number using Newton's Method.Examples: Input: N = 16, L = 0.0001 Output: 4 42 = 16Input: N = 327, L = 0.00001 Output: 18.0831 Newton's Method: Let N be any number then the square root of N can be given by the formula: root = 0.5 * (X + (N / X)) where X is any gu
7 min read
Check if a number is perfect square without finding square root
Check whether a number is a perfect square or not without finding its square root. Examples: Input: n = 36 Output: Yes Input: n = 12 Output: No Recommended PracticeCheck perfect squareTry It! Method 1:The idea is to run a loop from i = 1 to floor(sqrt(n)) and then check if squaring it makes n. Below is the implementation: C/C++ Code // C++ program
9 min read
Floor value Kth root of a number using Recursive Binary Search
Given two numbers N and K, the task is to find the floor value of Kth root of the number N. The Floor Kth root of a number N is the greatest whole number which is less than or equal to its Kth root.Examples: Input: N = 27, K = 3 Output: 3 Explanation: Kth root of 27 = 3. Therefore 3 is the greatest whole number less than equal to Kth root of 27. In
10 min read
Fast method to calculate inverse square root of a floating point number in IEEE 754 format
Given a 32-bit floating point number x stored in IEEE 754 floating point format, find the inverse square root of x, i.e., x-1/2.A simple solution is to do floating point arithmetic. Following is an example function. C/C++ Code #include <bits/stdc++.h> using namespace std; float InverseSquareRoot(float x) { return 1/sqrt(x); } int main() { cou
4 min read
Fifth root of a number
Given a number, print floor of 5'th root of the number.Examples: Input : n = 32 Output : 2 2 raise to power 5 is 32 Input : n = 250 Output : 3 Fifth square root of 250 is between 3 and 4 So floor value is 3. Method 1 (Simple) A simple solution is initialize result as 0, keep incrementing result while result5 is smaller than or equal to n. Finally r
10 min read
Find cubic root of a number
Given a number n, find the cube root of n.Examples: Input: n = 3 Output: Cubic Root is 1.442250 Input: n = 8 Output: Cubic Root is 2.000000 Recommended PracticeCube root of a numberTry It! We can use binary search. First we define error e. Let us say 0.0000001 in our case. The main steps of our algorithm for calculating the cubic root of a number n
7 min read
Primitive root of a prime number n modulo n
Given a prime number n, the task is to find its primitive root under modulo n. The primitive root of a prime number n is an integer r between[1, n-1] such that the values of r^x(mod n) where x is in the range[0, n-2] are different. Return -1 if n is a non-prime number. Examples: Input : 7 Output : Smallest primitive root = 3 Explanation: n = 7 3^0(
15 min read
Square root of a number using log
For a given number find the square root using log function. Number may be int, float or double. Examples: Input : n = 9Output : 3 Input : n = 2.93Output : 1.711724 We can find square root of a number using sqrt() method: C/C++ Code // C++ program to demonstrate finding // square root of a number using sqrt() #include<bits/stdc++.h> int main(v
3 min read
Square root of a number by Repeated Subtraction method
The Repeated Subtraction method for finding the square root of a number is an interesting approach. It involves repeatedly subtracting consecutive odd numbers from the number until you reach zero or a negative number. The number of times you can subtract is the approximate square root of the original number. Given an integer N, the task is to find
4 min read
Find square root of number upto given precision using binary search
Given a positive number n and precision p, find the square root of number upto p decimal places using binary search. Note : Prerequisite : Binary search Examples: Input : number = 50, precision = 3Output : 7.071Input : number = 10, precision = 4Output : 3.1622 We have discussed how to compute the integral value of square root in Square Root using B
9 min read
Root to leaf path sum equal to a given number
Given a binary tree and a sum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. Return false if no such path can be found. Example: Input: Output: True Explanation: Root to leaf path sum, existing in this tree are: 10 -> 8 -> 3 = 2110 -> 8 -> 5 = 2310 -> 2 -> 2
14 min read
Babylonian method for square root
Algorithm: This method can be derived from (but predates) Newton–Raphson method. 1 Start with an arbitrary positive start value x (the closer to the root, the better). 2 Initialize y = 1. 3. Do following until desired approximation is achieved. a) Get the next approximation for root using average of x and y b) Set y = n/x Implementation: C/C++ Code
9 min read
three90RightbarBannerImg