【算法】不使用库函数,求解立方根

牛客原题:https://www.nowcoder.com/practice/caf35ae421194a1090c22fe223357dca?tpId=37&tqId=21330&rp=1&ru=/exam/oj/ta&qru=/exam/oj/ta&sourceUrl=%2Fexam%2Foj%2Fta%3FtpId%3D37&difficulty=undefined&judgeStatus=undefined&tags=&title=
在这里插入图片描述
关键点:利用牛顿迭代公式~

const rl = require("readline").createInterface({
    input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

void (async function () {
   
    // Write your code here
    //  x^3 = a ,即 fx = x^3 -a
    // 牛顿迭代公式 下一次近似解 xn+1 = xn- f(x)/f'(x)
    while ((line = await readline())) {
   
        let tokens = line.split(" ");
        const a = parseFloat(tokens[0]);
        let x = a / 3; // 设定一个初始x值
        const tolerance = 1e-6; // 设置一个精度
        while (Math.abs(a - x * x * x) > tolerance) {
   
            const fx = x * x * x - a;
            x = x - fx / (3 * x * x);
        }
        console.log(parseFloat(x.toFixed(1)))
    }
})();

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-11 18:04:01       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-11 18:04:01       106 阅读
  3. 在Django里面运行非项目文件

    2024-01-11 18:04:01       87 阅读
  4. Python语言-面向对象

    2024-01-11 18:04:01       96 阅读

热门阅读

  1. 实现本地存储函数useLocalStorage

    2024-01-11 18:04:01       67 阅读
  2. bool和BOOL的区别

    2024-01-11 18:04:01       48 阅读
  3. LLaMA Efficient Tuning

    2024-01-11 18:04:01       53 阅读
  4. Redis的基本命令和数据类型

    2024-01-11 18:04:01       55 阅读
  5. QT第1天

    QT第1天

    2024-01-11 18:04:01      58 阅读
  6. 合泰HT32F65C40F 串口驱动 例:UART0 数据收发

    2024-01-11 18:04:01       67 阅读
  7. qemu dump dtb

    2024-01-11 18:04:01       55 阅读
  8. jsp页面 input传值提示不是有效数字

    2024-01-11 18:04:01       61 阅读
  9. IP版权交易里有哪些坑?合同和价格怎么定?

    2024-01-11 18:04:01       50 阅读