เราต้องเขียนฟังก์ชันหาค่ารากที่สองของตัวเลขโดยไม่ใช้ Math.sqrt()
ตัวอย่าง
โค้ดต่อไปนี้เป็นตัวอย่าง (ใช้ Binary Search):
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);
}
}
const findSqrt = num => {
let i = 1;
const found = false;
while (!found){
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));ผลลัพธ์
จะแสดงผลในคอนโซลดังนี้:
5.744562149047852
การทำงานของโค้ด
ลูปจาก i = 1 หา i ที่ i*i = n (perfect square) หรือ i*i > n แล้วใช้ Binary Search หาค่ารากที่สองในช่วง i-1 ถึง i