
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 Number Without Using Math.sqrt in JavaScript
We are required to write a JavaScript function that takes in a positive integer as the only argument. The function should find and return the square root of the number provided as the input.
Example
Following is the code −
const squareRoot = (num, precision = 0) => { if (num <= 0) { return 0; }; let res = 1; const deviation = 1 / (10 ** precision); while (Math.abs(num - (res ** 2)) > deviation) { res -= ((res ** 2) - num) / (2 * res); }; return Math.round(res * (10 ** precision)) / (10 ** precision); }; console.log(squareRoot(16)); console.log(squareRoot(161, 3)); console.log(squareRoot(1611, 4));
Output
Following is the output on console −
4 12.689 40.1373
Advertisements