0

I'm trying to make a set of functions that add the digits of a number. But with giant numbers, the maximum amount of calls is exceeded. I would like to resolve this issue.

My code - (Example of error in calling the function at the end.):

const recursiveSum = (arr, iter) => {
  let strNums = arr.reduce((acc, curr) => acc + curr, 0);
  let arrNums = strNums.toString().split('').map(Number);
  let res = arrNums.reduce((acc, curr) => acc + curr, 0);
  let newArr = res.toString().split('');

  const resLength = res.toString().split('').length;

  if (iter === 0 || resLength === 1) {
    return res;
  } else {
    return recursiveSum(newArr, iter - 1);
  }
}

function getTheP(arr, k, p) {
  console.log(k);
  arr.map(num => {
    p.push(num);
  });

  if (k === 0) {
    return p;
  } else {
    getTheP(arr, --k, p);
  }
}

function superDigit(n, k) {
  let p;
  const splitArr = n.toString().split('');

  p = getTheP(splitArr, k, []);

  const response = recursiveSum(p, k);

  return console.log(response);
}

superDigit('4757362', 10000);

  • 1
    How giant are giant numbers? – Konrad Jan 18 '23 at 19:14
  • 1
    Looks like superDigit makes a big number, then passes it to recursiveSum to sum the digits over and over. Call stack is exceeded generating the digits, in getTheP, not in recursiveSum. – Trevor Dixon Jan 18 '23 at 19:24
  • Apparently Chrome doesn't do tail-call optimization. Make it an iterative thing and it should work. – Trevor Dixon Jan 18 '23 at 19:29
  • @TrevorDixon I didn't hear about any js engine that would do that ; oh, there is [safari lol](https://stackoverflow.com/a/37224563/5089567) – Konrad Jan 18 '23 at 19:33
  • Konrad - is a very, very big number. And the k in superDigit will tell us how many times the number (the "n" variable) will repeat itself. – Lucas Junqueira Jan 20 '23 at 00:57
  • What is the point of `getTheP`? You attempt to create a huge array only to immediately sum it up. Instead, use simple multiplication. – Bergi Jan 20 '23 at 01:49

0 Answers0