JavaScript 中不使用 Math.sqrt() 求平方根函式


我們需要編寫一個 JavaScript 函式,該函式取一個數字並計算其平方根,而不使用 Math.sqrt() 函式。

因此,讓我們編寫此函式的程式碼 -

示例

程式碼如下 -

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));

理解程式碼

我們從 i = 1 迴圈。如果 i * i = n,則我們返回 i,因為 n 是一個完美平方,其平方根為 I,否則我們找到最小的 i,其中 i * i 剛剛大於 n。

現在我們知道 n 的平方根位於間隔 i - 1 和 i 中。

然後我們使用二分搜尋演算法來找到平方根。

輸出

控制檯中的輸出將為 -

5.744562149047852

更新日期:2020 年 10 月 22 日

4K+ 瀏覽量

開啟你的 職業生涯

完成課程取得認證

開始
廣告