Describes computing the cube root of a number without using library functions. Keep one decimal place.
Input description: Parameter to be evaluated, of type double (a real number)
Output description: Cube root of input parameter. Keep one decimal place.
Example 1 Input: 216 Output: 6.0
Example 2 Input: -0.07 Output: -0.4
Example 3 Input: -5 Output: -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(letj=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] = =The '-'){
minus = true;
line = line.substring(1); }let dotIndex = line.indexOf('. ');
if(dotIndex>-1){
line = (Number(line)*1000).toString();
factor = 1;// The cube root needs to be reduced by 10 times
//factor = line.substring(dotIndex+1).length;
}
try{
//line = line.replace('.','')
let tmpResult = myProcess(line);
if(minus) {// Negative numbers need to be corrected
tmpResult = Number(Number(Number(tmpResult)-0.1).toFixed(1));
}
tmpResult = Number(tmpResult)/(10**factor);
tmpResult = tmpResult.toFixed(1);
if(minus) {
tmpResult = The '-'+tmpResult;
}
console.log(tmpResult);
}catch(e){
console.log(line); }});Copy the code