Skip to content

Commit cf31916

Browse files
committed
squareRoot.js
1 parent 2a93534 commit cf31916

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// 2. Find the Square Root
2+
3+
function squareRoot(n) {
4+
return Math.sqrt(n);
5+
}
6+
console.log(squareRoot(144));
7+
8+
const squareRootUsingPow = (n) => Math.pow(n, 1 / 2);
9+
10+
console.log(squareRootUsingPow(169));
11+
12+
//Using Binary Search
13+
14+
function findSqrt(number) {
15+
let start = 0,
16+
end = number,
17+
mid,
18+
ans;
19+
20+
while (start < end) {
21+
mid = Math.floor((start + end) / 2);
22+
23+
if (mid * mid === number) {
24+
ans = mid;
25+
break;
26+
}
27+
28+
if (mid * mid < number) {
29+
ans = start;
30+
start = mid + 1;
31+
} else {
32+
end = mid - 1;
33+
}
34+
}
35+
36+
let increment = 0.1;
37+
38+
for (let i = 0; i < 5; i++) {
39+
while (ans * ans <= number) {
40+
ans += increment;
41+
}
42+
ans = ans - increment;
43+
increment = increment / 10;
44+
}
45+
return ans;
46+
}
47+
48+
49+
console.log(findSqrt(256));

0 commit comments

Comments
 (0)