不用库函数 用JS实现任意精度数值(包括负数以及小数)的开立方根

414 阅读1分钟

描述 计算一个数字的立方根,不使用库函数。 保留一位小数。

输入描述: 待求解参数,为double类型(一个实数)

输出描述: 输入参数的立方根。保留一位小数。

示例1
输入:
216
输出:
6.0

示例2
输入:
-0.07
输出:
-0.4

示例3
输入:
-5
输出:
-1.7

const readline = require('readline');


function myProcess(str)
{   
    let tmpNum = BigInt(str);
    let tmpValue =  tmpNum;
    let lastBig;
    let firstLittle;
    tmpValue = (BigInt)(tmpValue / BigInt(2));
    while(true) {
         if(tmpValue**BigInt(3) === tmpNum){
            firstLittle = tmpValue;
            break;
        } else if(tmpValue**BigInt(3) > tmpNum){
            lastBig = tmpValue;
            tmpValue = (BigInt)(tmpValue / BigInt(2));
        } else{
            firstLittle = tmpValue;
            break;
        }
    }
    
    let i=firstLittle;
    for(i=firstLittle;i<lastBig;i++){
        if(BigInt(i)**BigInt(3) > tmpNum)
            break;
    }
    let start = Number(i) - 1;
    let step = 0.1;
    let result;
    for(let j=start;j<start+1;){
        if((BigInt(j*10)**BigInt(3) / BigInt(1000)) > tmpNum){
            result = j;
            break;
        }
        j += 0.1; 
        j = Number(Number(j).toFixed(1));
    }

    if ((BigInt(result*10)**BigInt(3) - tmpNum*BigInt(1000)) < (tmpNum*BigInt(1000) - BigInt(Number(Number(result-0.1).toFixed(1))*10)**BigInt(3))){
        result = Number(result).toString();
    } else {
        result = Number(Number(result-0.1).toFixed(1)).toString();
    }
    if(result.length == 1){
        result+='.0';
    }
    return result;
}


const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.on('line', function (line) {
    let minus = false;
    let factor = 0;
    if(line[0]=='-'){
        minus = true;
        line = line.substring(1) ;

    }
    let dotIndex = line.indexOf('.');
    if(dotIndex>-1){
        line = (Number(line)*1000).toString();
        factor = 1;//扩大1000倍,立方根需缩小10倍
        //factor = line.substring(dotIndex+1).length;
    }

    try{
        //line = line.replace('.','')
        let tmpResult = myProcess(line);
        if(minus) {//负数需矫正
            tmpResult = Number(Number(Number(tmpResult)-0.1).toFixed(1)); 
        }
        tmpResult = Number(tmpResult)/(10**factor);
        tmpResult = tmpResult.toFixed(1);
        if(minus) {
            tmpResult = '-'+tmpResult;
        }
        console.log(tmpResult);
    }catch(e){
        console.log(line);
    }
     
});