The Wayback Machine - https://web.archive.org/web/20241012032812/https://www.geeksforgeeks.org/find-root-of-a-number-using-newtons-method/
Open In App

Find root of a number using Newton’s method

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

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 = 16
Input: 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 guess which can be assumed to be N or 1. 
 

 

  • In the above formula, X is any assumed square root of N and root is the correct square root of N.
  • Tolerance limit is the maximum difference between X and root allowed.

Approach: The following steps can be followed to compute the answer: 
 

  1. Assign X to the N itself.
  2. Now, start a loop and keep calculating the root which will surely move towards the correct square root of N.
  3. Check for the difference between the assumed X and calculated root, if not yet inside tolerance then update root and continue.
  4. If the calculated root comes inside the tolerance allowed then break out of the loop.
  5. Print the root.

Below is the implementation of the above approach: 
 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the square root of
// a number using Newtons method
double squareRoot(double n, float l)
{
    // Assuming the sqrt of n as n only
    double x = n;
 
    // The closed guess will be stored in the root
    double root;
 
    // To count the number of iterations
    int count = 0;
 
    while (1) {
        count++;
 
        // Calculate more closed x
        root = 0.5 * (x + (n / x));
 
        // Check for closeness
        if (abs(root - x) < l)
            break;
 
        // Update root
        x = root;
    }
 
    return root;
}
 
// Driver code
int main()
{
    double n = 327;
    float l = 0.00001;
 
    cout << squareRoot(n, l);
 
    return 0;
}


Java




// Java implementation of the approach
class GFG
{
     
    // Function to return the square root of
    // a number using Newtons method
    static double squareRoot(double n, double l)
    {
        // Assuming the sqrt of n as n only
        double x = n;
     
        // The closed guess will be stored in the root
        double root;
     
        // To count the number of iterations
        int count = 0;
     
        while (true)
        {
            count++;
     
            // Calculate more closed x
            root = 0.5 * (x + (n / x));
     
            // Check for closeness
            if (Math.abs(root - x) < l)
                break;
     
            // Update root
            x = root;
        }
     
        return root;
    }
     
    // Driver code
    public static void main (String[] args)
    {
        double n = 327;
        double l = 0.00001;
     
        System.out.println(squareRoot(n, l));
    }
}
 
// This code is contributed by AnkitRai01


Python3




# Python3 implementation of the approach
 
# Function to return the square root of
# a number using Newtons method
def squareRoot(n, l) :
 
    # Assuming the sqrt of n as n only
    x = n
 
    # To count the number of iterations
    count = 0
 
    while (1) :
        count += 1
 
        # Calculate more closed x
        root = 0.5 * (x + (n / x))
 
        # Check for closeness
        if (abs(root - x) < l) :
            break
 
        # Update root
        x = root
 
    return root
 
# Driver code
if __name__ == "__main__" :
 
    n = 327
    l = 0.00001
 
    print(squareRoot(n, l))
 
# This code is contributed by AnkitRai01


C#




// C# implementation of the approach
using System;
 
class GFG
{
     
    // Function to return the square root of
    // a number using Newtons method
    static double squareRoot(double n, double l)
    {
        // Assuming the sqrt of n as n only
        double x = n;
     
        // The closed guess will be stored in the root
        double root;
     
        // To count the number of iterations
        int count = 0;
     
        while (true)
        {
            count++;
     
            // Calculate more closed x
            root = 0.5 * (x + (n / x));
     
            // Check for closeness
            if (Math.Abs(root - x) < l)
                break;
     
            // Update root
            x = root;
        }
     
        return root;
    }
     
    // Driver code
    public static void Main()
    {
        double n = 327;
        double l = 0.00001;
     
        Console.WriteLine(squareRoot(n, l));
    }
}
 
// This code is contributed by AnkitRai01


Javascript




<script>
    // Javascript implementation of the approach
     
    // Function to return the square root of
    // a number using Newtons method
    function squareRoot(n, l)
    {
        // Assuming the sqrt of n as n only
        let x = n;
       
        // The closed guess will be stored in the root
        let root;
       
        // To count the number of iterations
        let count = 0;
       
        while (true)
        {
            count++;
       
            // Calculate more closed x
            root = 0.5 * (x + (n / x));
       
            // Check for closeness
            if (Math.abs(root - x) < l)
                break;
       
            // Update root
            x = root;
        }
       
        return root.toFixed(4);
    }
     
    let n = 327;
    let l = 0.00001;
 
    document.write(squareRoot(n, l));
  
 // This code is contributed by divyesh072019.
</script>


Output

18.0831




Time Complexity: O(log N)

Auxiliary Space: O(1)

Recursive Approach:

  • Start by defining the function findSqrt that takes three arguments – the number whose square root is to be found N, the current guess guess, and the tolerance level tolerance.
  • Compute the next guess using the Newton’s formula next_guess = (guess + N/guess) / 2.
  • Check if the difference between the current guess and the next guess is <= tolerance level tolerance using the abs() function. If the condition is satisfied, return the next guess.
  • Otherwise, recursively call the findSqrt function with the new guess.
  • Last print the result

Below is the implementation of the above approach: 

C++




#include <iostream>
#include <cmath>
 
using namespace std;
 
double findSqrt(double N, double guess, double tolerance)
{
    double next_guess = (guess + N/guess) / 2;
    if (abs(guess - next_guess) <= tolerance) {
        return next_guess;
    }
    else {
        return findSqrt(N, next_guess, tolerance);
    }
}
 
int main()
{
    double N=327, L=0.00001;
    double guess = N/2; // Initialize the guess to N/2
    double sqrt = findSqrt(N, guess, L);
    cout << sqrt << endl;
    return 0;
}


Java




public class Main {
    public static double findSqrt(double N, double guess,
                                  double tolerance)
    {
        double nextGuess = (guess + N / guess) / 2;
        if (Math.abs(guess - nextGuess) <= tolerance) {
            return nextGuess;
        }
        else {
            return findSqrt(N, nextGuess, tolerance);
        }
    }
 
    public static void main(String[] args)
    {
        double N = 327, L = 0.00001;
        double guess = N / 2; // Initialize the guess to N/2
        double sqrt = findSqrt(N, guess, L);
        System.out.printf("%.4f%n", sqrt);
    }
}
 
// This code is contributed by Samim Hossain Mondal.


Python3




def find_sqrt(N, guess, tolerance):
    next_guess = (guess + N / guess) / 2
    if abs(guess - next_guess) <= tolerance:
        return next_guess
    else:
        return find_sqrt(N, next_guess, tolerance)
 
if __name__ == "__main__":
    N = 327
    tolerance = 0.00001
    guess = N / 2  # Initialize the guess to N/2
    sqrt = find_sqrt(N, guess, tolerance)
    sqrt = round(sqrt, 4)
    print(sqrt)


C#




using System;
 
class Program
{
    static double FindSqrt(double N, double guess, double tolerance)
    {
        double nextGuess = (guess + N / guess) / 2;
        if (Math.Abs(guess - nextGuess) <= tolerance)
        {
            return nextGuess;
        }
        else
        {
            return FindSqrt(N, nextGuess, tolerance);
        }
    }
 
    static void Main()
    {
        double N = 327;
        double tolerance = 0.00001;
        double guess = N / 2; // Initialize the guess to N/2
        double sqrt = FindSqrt(N, guess, tolerance);
        sqrt = Math.Round(sqrt, 4);
        Console.WriteLine(sqrt);
    }
}


Javascript




function findSqrt(N, guess, tolerance) {
    let nextGuess = (guess + N / guess) / 2;
    if (Math.abs(guess - nextGuess) <= tolerance) {
        return nextGuess;
    } else {
        return findSqrt(N, nextGuess, tolerance);
    }
}
 
let N = 327;
let tolerance = 0.00001;
let guess = N / 2; // Initialize the guess to N/2
let sqrt = findSqrt(N, guess, tolerance);
console.log(sqrt.toFixed(4));


Output

18.0831





Time Complexity: O(log N), where N is the input number.

Auxiliary Space: O(log N)



Previous Article
Next Article

Similar Reads

Program for Newton Raphson Method
Given a function f(x) on floating number x and an initial guess for root, find root of function in interval. Here f(x) represents algebraic or transcendental equation. For simplicity, we have assumed that derivative of function is also provided as input.Example: Input: A function of x (for example x3 – x2 + 2), derivative function of x (3x2 – 2x fo
9 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
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
Newton's Divided Difference Interpolation Formula
Interpolation is an estimation of a value within two known values in a sequence of values. Newton's divided difference interpolation formula is an interpolation technique used when the interval difference is not same for all sequence of values. Suppose f(x0), f(x1), f(x2).........f(xn) be the (n+1) values of the function y=f(x) corresponding to the
11 min read
Newton Forward And Backward Interpolation
Interpolation is the technique of estimating the value of a function for any intermediate value of the independent variable, while the process of computing the value of the function outside the given range is called extrapolation. Forward Differences: The differences y1 – y0, y2 – y1, y3 – y2, ......, yn – yn–1 when denoted by dy0, dy1, dy2, ......
15+ min read
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
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
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
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
Program to find root of an equations using secant method
The secant method is used to find the root of an equation f(x) = 0. It is started from two distinct estimates x1 and x2 for the root. It is an iterative procedure involving linear interpolation to a root. The iteration stops if the difference between two intermediate values is less than the convergence factor. Examples : Input : equation = x3 + x -
8 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
Long Division Method to find Square root with Examples
Given an integer X which is a perfect square, the task is to find the square root of it by using the long division method. Examples: Input: N = 484 Output: 22 222 = 484 Input: N = 144 Output: 12 122 = 144 Approach: Long division is a very common method to find the square root of a number. The following is the stepwise solution for this method: 1. D
10 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
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
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
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
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
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
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
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
Find the root of the sub-tree whose weighted sum XOR with X is maximum
Given a tree, and the weights of all the nodes, the task is to find the root of the sub-tree whose weighted sum XOR with given integer X is maximum.Examples: Input: X = 15 Output: 4 Weight of sub-tree for parent 1 = ((-1) + (5) + (-2) + (-1) + (3)) XOR 15 = 4 XOR 15 = 11 Weight of sub-tree for parent 2 = ((5) + (-1) + (3)) XOR 15 = 7 XOR 15 = 8 Wei
7 min read
Iterative program to find distance of a node from root
Given the root of a binary tree and a key x in it, find the distance of the given key from the root node. Dis­tance means num­ber of edges between two nodes. Examples: Input : x = 45, 5 is Root of below tree 5 / \ 10 15 / \ / \ 20 25 30 35 \ 45 Output : Distance = 3 There are three edges on path from root to 45. For more understanding of question,
9 min read
Find the root of the sub-tree whose weighted sum is minimum
Given a tree, and the weights of all the nodes, the task is to find the root of the sub-tree whose weighted sum is minimum. Examples: Input: Output: 5 Weight of sub-tree for parent 1 = ((-1) + (5) + (-2) + (-1) + (3)) = 4 Weight of sub-tree for parent 2 = ((5) + (-1) + (3)) = 7 Weight of sub-tree for parent 3 = -1 Weight of sub-tree for parent 4 =
7 min read
Find the root of the sub-tree whose weighted sum XOR with X is minimum
Given a tree, and the weights of all the nodes, the task is to find the root of the sub-tree whose weighted sum XOR with given integer X is minimum.Examples: Input: X = 15 Output: 5 Weight of sub-tree for parent 1 = ((-1) + (5) + (-2) + (-1) + (3)) XOR 15 = 4 XOR 15 = 11 Weight of sub-tree for parent 2 = ((5) + (-1) + (3)) XOR 15 = 7 XOR 15 = 8 Wei
7 min read
Find direction of path followed from root by a linked list in a Binary Tree
Given root of the Binary Tree T and a linked list L, the task is to find the direction of path followed from root such that there exists a path from root to any leaf node of the Tree such that the values is that path forms the Linked List. If there doesn't exist any such path then print "-1". Note: The path taken in the left direction is denoted by
13 min read
Find the path from root to the given nodes of a tree for multiple queries
Given a tree with N vertices numbered from 0 to N - 1 (0th node is the root node). Also, given q queries containing nodes in the tree. The task is to find the path from the root node to the given node for multiple queries. Examples: Input: N = 6, q[] = {2, 4} Tree: 0 / \ 1 2 | 3 / \ 4 5 Output: 0 2 0 1 3 4 The path from root node to node 2 is 0 -
10 min read
Find distance of nodes from root in a tree for multiple queries
Given a tree with N vertices numbered from 0 to N – 1 and Q queries containing nodes in the tree, the task is to find the distance of given node from root node for multiple queries. Consider 0th node as the root node and take the distance of the root node from itself as 0.Examples: Tree: 0 / \ 1 2 | / \ 3 4 5 Input: 2 Output: 1 Explanation: Distanc
8 min read
Find the root of given non decreasing function between A and B
Given three numbers a, b, and c that forms a monotonically increasing function [Tex]f(x) [/Tex]of the form a*x2 + b*x + c and two number A and B, the task is to find the root of the function i.e., find the value of x such that [Tex]f(x) = 0 [/Tex]where A ? x ? B. Examples: Input: a = 2, b = -3, c = -2, A = 0, B = 3 Output: 2.0000 Explanation: f(x)
8 min read
Find maximum GCD value from root to leaf in a Binary tree
Given a Binary Tree, the task is to find the maximum value of GCD from any path from the root node to the leaf node. Examples: Input: Below is the given tree: Output: 3Explanation:Path 1: 15->3->5 = gcd(15, 3, 15) =3Path 2: 15->3->1 =gcd(15, 3, 1) = 1Path 3: 15->7->31=gcd(15, 7, 31)= 1Path 4: 15->7->9 = gcd(15, 7, 9) =1, out
8 min read
Practice Tags :