const sqrtSearch = (num, start, end) => {
const mid = (start + end) / 2;
const product = mid * mid;
if (product === num || Math.abs(product - num) < 0.00000000000001) { // less than 1 100 trillionth
return mid;
} else if (product > num) {
return sqrtSearch(num, start, mid);
} else {
return sqrtSearch(num, mid, end);
}
};
// const sqrt = (num) => {
// let i = 0;
// while (true) {
// const product = i * i;
// if (product === num) {
// return i;
// } else if (product > num) {
// // binary search
// return sqrtSearch(num, i - 1, i);
// }
// i++;
// }
// };
const sqrt = (n) => {
let x = n;
let root;
while (true) {
root = 0.5 * (x + (n / x));
if (Math.abs(root - x) < 0.00001) {
break;
}
x = root;
}
return root;
};
console.log('just binary search', sqrtSearch(30, 1, 30), Math.sqrt(30));
console.log(sqrt(30), Math.sqrt(30));
console.log(sqrt(26), Math.sqrt(26));
console.log(sqrt(10000), Math.sqrt(10000));
// const sqrtSearch = (num, start, end) => {
// // num = 5, start = 2, end = 3
// // num = 5, start 2, end 2.5
// const mid = (start + end) / 2;
// const product = mid * mid;
// if (product === num || Math.abs(product - num) < 0.00001) {
// return mid;
// } else if (product > num) {
// return sqrtSearch(num, start, mid);
// } else {
// return sqrtSearch(num, mid, end);
// }
// };
// const sqrt = (num) => {
// let i = 0;
// while (true) {
// const product = i * i;
// if (product === num) {
// return i;
// } else if (product > num) {
// // do binary search
// return sqrtSearch(num, i - 1, i);
// }
// i++;
// }
// };
// const getRoundedValue = (val) => Math.floor(val * 100000) / 100000;
// console.log(getRoundedValue(sqrt(5)), getRoundedValue(Math.sqrt(5)));
// console.log(getRoundedValue(sqrt(5)) === getRoundedValue(Math.sqrt(5)));
// console.log(sqrt(4), Math.sqrt(4));
// console.log(sqrt(4) === Math.sqrt(4));