Solving Recursion Algorithm Problem

Photo by Mario Mesaglio on Unsplash

Problem 1: Recursive Digit Sum

We are given the task to solve for the super digit, which is the digit that is sum of a longer digit. Our known variables are n and k, n represents the large number that is a string and k represents the total amount of times n is concatenated. In the example below n is ‘9875’ and i is 4. The variable p is the result of concatenating n, so the amount is ‘9875987598759875’. However since this amount is in a string, we must separate the individual element from the overall string and then change it from a string to a number in order to sum the individual numbers together. We continue to do this until the length of the number is 1, and thus we get our super digit which is 8.

superDigit(p) = superDigit(9875987598759875)
9+8+7+5+9+8+7+5+9+8+7+5+9+8+7+5 = 116
superDigit(p) = superDigit(116)
1+1+6 = 8
superDigit(p) = superDigit(8)

The solution:

function superDigit(n, k) {if (n.length === 1) return nconst digit = (n.split('').reduce((res, d) => res + Number(d), 0) * k) + ''return superDigit(digit, 1)}

In the code above, we set our base case with the if statement. If the length of n is equal to 1, we will return n. The following code we name our constant variable digit, and with digit we split the large string amount to individual string elements and then we use the reduce method to add up all the amounts which we define within the parenthesis. In it we have the accumulator as res (result) and the current value as d. Then within the arrow function we add the res to d in which we used the Number method to change it from a string to a number and afterwards we multiply by k and then lastly change it back to a string. And of course our last line of code will be to call the superDigit function with the parameters digit and 1 so that if the amount is still not just a number it will get passed through the function again.