Quickly calculate the cube root of 6 digit numbers

Technology CommunityCategory: JavaScriptQuickly calculate the cube root of 6 digit numbers
VietMX Staff asked 3 years ago
Problem

For example, if the input is 636056 then your program should output 86.

The general algorithm is as follows: 1. Store the first 10 cube roots, their cubes, and the last digit in the number.

var cubes_10 = {
     '0': 0,
     '1': 1,
     '8': 8,
    '27': 7,
    '64': 4,
   '125': 5,
   '216': 6,
   '343': 3,
   '512': 2,
   '729': 9
 };
  1. Ignore the last 3 digits of the input number, and for the remaining numbers, find the cube in the table that is less than or equal to the remaining number, and take the corresponding cube root to be the first number in your answer.
  2. For the last 3 digits that you previously ignored, loop through the table and when you get to the ith index, where i equals the last digit of the remaining 3 numbers, take the corresponding number in the right column as your answer.
  3. These numbers combined are the cube root answer.
function fastCubeRoot(num) {
  
  var cubes_10 = {
      '0': 0,
      '1': 1,
      '8': 8,
     '27': 7,
     '64': 4,
    '125': 5,
    '216': 6,
    '343': 3,
    '512': 2,
    '729': 9
  };
  
  // get last 3 numbers and the remaining numbers
  var arr = num.toString().split('');
  var last = arr.slice(-3);
  var first = parseInt(arr.slice(0, -3).join(''));
  
  // answer will be stored here
  var lastDigit = 0, firstDigit = 0, index = 0;
  
  // get last digit of cube root
  for (var i in cubes_10) {
    if (index === parseInt(last[last.length-1])) { lastDigit = cubes_10[i]; }
    index++;
  }
  
  // get first digit of cube root
  index = 0;
  for (var i in cubes_10) {
    if (parseInt(i) <= first) { firstDigit = index; }
    index++;
  }
  
  // return cube root answer
  return firstDigit + '' + lastDigit;
  
}

fastCubeRoot(830584);