JavaScript Program to Find the Square Root

Given a number N, the task is to calculate the square root of a given number using JavaScript. There are the approaches to calculate the square root of the given number, these are:

Approaches to Find the Square Root of Given Number in JavaScript:

Table of Content

  • Using Math.sqrt() Method
  • Using JavaScript Math.pow() Method
  • Using Binary Search
  • Newton’s Method

Basic Examples:

Input: num = 25
Output: 2
Explanation: The square root of 25 is 5.
Input: num = -120
Output: NaN
Explanation: The square root of Negative numbers is NaN.
Input: num = 'Beginner'
Output: NaN
Explanation: The square root of String Value is NaN.

Using Math.sqrt() Method

The Math.sqrt() method is used to find the Square Root of a given number.

Syntax:

Math.sqrt( value )

Example: In this example we will find the square root using JavaScript Math.sqrt() method.

Javascript
const num1 = 25;
const num2 = -120;
const num3 = 'Beginner';

// Math.sqrt() function returns the
// square root of number
console.log('Square Root of ' + 
    num1 + ' is ' + Math.sqrt(num1));
  
// Math.sqrt() function returns NaN, because
// the passed value is negative integer
console.log('Square Root of ' + 
    num2 + ' is ' + Math.sqrt(num2));
    
// Math.sqrt() function returns NaN, because
// the passed value is string
console.log('Square Root of ' + 
    num3 + ' is ' + Math.sqrt(num3));

Output
Square Root of 25 is 5
Square Root of -120 is NaN
Square Root of Beginner is NaN

Using JavaScript Math.pow() Method

The Math.pow() method is used calculate the power a number i.e., the value of the number raised to some exponent. To get the square root of any Number, we set the power to 1/2 of that number.

Syntax:

Math.pow( num, 1/2 )

Example: In this example, we will calculate the square root of given values using Math.pow() method.

Javascript
const num1 = 25;
const num2 = -120;
const num3 = 'Beginner';

// Math.pow() function returns the
// square root of number
console.log('Square Root of ' + 
    num1 + ' is ' + Math.pow(num1, 1/2));
  
// Math.pow() function returns NaN, because
// the passed value is negative integer
console.log('Square Root of ' + 
    num2 + ' is ' + Math.pow(num2, 1/2));
    
// Math.pow() function returns NaN, because
// the passed value is string
console.log('Square Root of ' + 
    num3 + ' is ' + Math.pow(num3, 1/2));

Output
Square Root of 25 is 5
Square Root of -120 is NaN
Square Root of Beginner is NaN

Using Binary Search

The binary search is used to find the square root of the given number N with precision upto 5 decimal places. 

  • The square root of number N lies in range 0 ? squareRoot ? N. Initialize start = 0 and end = number.
  • Compare the square of the mid integer with the given number. If it is equal to the number, then we found our integral part, else look for the same in the left or right side of mid depending upon the condition.
  • After finding an integral part, we will find the fractional part.
  • Initialize the increment variable by 0.1 and iteratively calculate the fractional part upto 5 decimal places.
  • For each iteration, change increment to 1/10th of its previous value.
  • Finally, return the answer computed.

Example: In this article, we will calculate the square root of the given Number using Binary Search.

Javascript
// Function to find the square-root of N
function findSqrt(number) {
    let start = 0, end = number, mid, ans;

    // To find integral part of square
    // root of number
    while (start <= end) {

        // Find mid
        mid = Math.floor((start + end) / 2);

        // If number is perfect square
        // then break
        if (mid * mid == number) {
            ans = mid;
            break;
        }

        // Increment start if integral
        // part lies on right side
        // of the mid
        if (mid * mid < number) {

            // First start value should be
            // added to answer
            ans = start;

            // Then start should be changed
            start = mid + 1;
        }

        // Decrement end if integral part
        // lies on the left side of the mid
        else {
            end = mid - 1;
        }
    }

    // To find the fractional part
    // of square root upto 5 decimal
    let increment = 0.1;

    for (let i = 0; i < 5; i++) {
        while (ans * ans <= number) {
            ans += increment;
        }

        // Loop terminates,
        // when ans * ans > number
        ans = ans - increment;
        increment = increment / 10;
    }
    return ans;
}

// Driver Code
const n = 36;

console.log(findSqrt(n));

Output
6

Newton’s Method

Newton’s method, also known as the Newton-Raphson method, is an iterative method for finding the roots of a real-valued function. To find the square root of a number using Newton’s method:

  1. Start with an initial guess ?0x0​ for the square root.
  2. Iterate using the formula ??+1=1/2(??+??????/??)until the result converges to the desired accuracy.

Here’s how we can implement Newton’s method to find the square root of a given number in JavaScript:

JavaScript
function findSquareRootUsingNewton(number) {
    if (number < 0) return NaN; // Square root of negative numbers is NaN

    let guess = number / 2; // Initial guess

    // Iterate until the guess converges
    while (Math.abs(guess * guess - number) > Number.EPSILON) {
        guess = (guess + number / guess) / 2;
    }

    return guess;
}

// Test Cases
console.log("Square root of 25:", findSquareRootUsingNewton(25)); // Output: 5
console.log("Square root of -120:", findSquareRootUsingNewton(-120)); // Output: NaN
console.log("Square root of 'Beginner':", findSquareRootUsingNewton('Beginner')); // Output: NaN

Output
Square root of 25: 5
Square root of -120: NaN
Square root of 'Beginner': NaN