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 library functions - JavaScript
We are required to write a JavaScript function that takes in a number and calculates its square root without using the Math.sqrt() function.
Example
Following is the code −
const square = (n, i, j) => {
let mid = (i + j) / 2;
let mul = mid * mid;
if ((mul === n) || (Math.abs(mul - n) < 0.00001)){
return mid;
}else if (mul < n){
return square(n, mid, j);
}else{
return square(n, i, mid);
}
}
// Function to find the square root of n
const findSqrt = num => {
let i = 1;
const found = false;
while (!found){
// If n is a perfect square
if (i * i === num){
return i;
}else if (i * i > num){
let res = square(num, i - 1, i);
return res;
};
i++;
}
}
console.log(findSqrt(33));
Output
This will produce the following output in console −
5.744562149047852
Understanding the code
We looped over from i = 1.
If i * i = n, then we returned i as n is a perfect square whose square root is i., else we find the smallest i for which i * i is just greater than n.
Now we know the square root of n lies in the interval i – 1 and i. And then we used the Binary Search algorithm to find the square root.
Advertisements