- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding square root of a non-negative number without using Math.sqrt() JavaScript
We are required to write a JavaScript function that takes in a non-negative Integer and computes and returns its square root. We can floor off a floating-point number to an integer.
For example: For the number 15, we need not to return the precise value, we can just return the nearest smaller integer value that will be 3, in case of 15
We will make use of the binary search algorithm to converse to the square root of the given number.
The code for this will be −
Example
const squareRoot = (num = 1) => { let l = 0; let r = num; while(l <= r) { const mid = Math.floor((l + r) / 2); if(mid ** 2 === num){ return mid; }else if(mid ** 2 > num){ r = mid - 1; } else{ l = mid + 1; }; }; return r; }; console.log(squareRoot(4)); console.log(squareRoot(729)); console.log(squareRoot(15)); console.log(squareRoot(54435));
Output
And the output in the console will be −
2 27 3 233
- Related Articles
- Finding square root of a number without using Math.sqrt() in JavaScript
- Square root function without using Math.sqrt() in JavaScript
- Finding square root of a number without using library functions - JavaScript
- Get square root of a number using Math.sqrt in Java
- Check if a number is perfect square without finding square root in C++
- Finding the longest non-negative sum sequence using JavaScript
- Return the non-negative square-root of an array element-wise in Numpy
- How to get the square root of a number in JavaScript?
- 8086 program to find the square root of a perfect square root number
- Finding array number that have no matching positive or negative number in the array using JavaScript
- How to perform square root without using math module in Python?
- Find the number of digit in the square root of the given number ( without any calculation): $529$.
- Find the number of digit in the square root of the given number ( without any calculation): $1444$.
- Find the number of digit in the square root of the given number ( without any calculation): $17161$.
- Find the number of digit in the square root of the given number ( without any calculation): $4601025$.

Advertisements