-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsquareRoot.js
More file actions
executable file
·49 lines (37 loc) · 789 Bytes
/
squareRoot.js
File metadata and controls
executable file
·49 lines (37 loc) · 789 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// 2. Find the Square Root
function squareRoot(n) {
return Math.sqrt(n);
}
console.log(squareRoot(144));
const squareRootUsingPow = (n) => Math.pow(n, 1 / 2);
console.log(squareRootUsingPow(169));
//Using Binary Search
function findSqrt(number) {
let start = 0,
end = number,
mid,
ans;
while (start < end) {
mid = Math.floor((start + end) / 2);
if (mid * mid === number) {
ans = mid;
break;
}
if (mid * mid < number) {
ans = start;
start = mid + 1;
} else {
end = mid - 1;
}
}
let increment = 0.1;
for (let i = 0; i < 5; i++) {
while (ans * ans <= number) {
ans += increment;
}
ans = ans - increment;
increment = increment / 10;
}
return ans;
}
console.log(findSqrt(256));