Project Euler 20 test cases not working

Tell us what’s happening:
The test cases are not passing but the value which is being returned by the function is correct. The code is correct and the return value can be verified using console.log()

Your code so far

const v = [1];

function multiply(n) {
let carry = 0;
let size = v.length;

/*
Explanation:
      2 1
        7 4         4 * 3 = 12          => 1 carry and 2 is the digit 
        x 3         1 + (7 * 3) = 22    => 2 carry and 2 is the digit
    --------        then placing each digit of the carry in the next array index  => 2 is the next digit
      2 2 2 
*/

for (let i = 0; i < size; i++)
{
    let result = (v[i] * n) + carry;        
    v[i] = result % 10;
    carry = Math.floor(result / 10);
}

while (carry != 0)
{
    v.push(carry % 10);
    carry = Math.floor(carry / 10);
}
}

function sumFactorialDigits(num) {
for (let i = 1; i <= num; i++)
    multiply(i);

const sumOfDigits = v.reduce((sum, digit) => sum + Number(digit), 0);
return sumOfDigits;
}

sumFactorialDigits(10);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36 Edg/91.0.864.59

Challenge: Problem 20: Factorial digit sum

Link to the challenge:

Your code contains global variables that are changed each time the function is run. This means that after each test completes, subsequent tests start with the previous value. To fix this, make sure your function doesn’t change any global variables, and declare/assign variables within the function if they need to be changed.

Example:

var myGlobal = [1];
function returnGlobal(arg) {
  myGlobal.push(arg);
  return myGlobal;
} // unreliable - array gets longer each time the function is run

function returnLocal(arg) {
  var myLocal = [1];
  myLocal.push(arg);
  return myLocal;
} // reliable - always returns an array of length 2
1 Like

Thank you so much. This worked and I couldn’t have thought of it. Declaring it in one function and passing it as an argument to the other worked :smile:

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.