Home > front end >  having trouble getting the sum of multiples below an inputted number?
having trouble getting the sum of multiples below an inputted number?

Time:06-28

recently i got this question on codewar and was trying to solve it: " If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in. Additionally, if the number is negative, return 0 (for languages that do have them).

Note: If the number is a multiple of both 3 and 5, only count it once. "

the code would be all over by now if its werent for the inclusion of the requirement "multiple of both...count it once".

i tried to solve it through the use of arrays and if else statements as you can see from my codes attached, but i hit a wall in the form of an error telling me the reduce command can't perform on an empty array, when i did consider that situation and put an if statement for when the intersectionResult is undefined. help regarding more detail on the error, the proper syntax to solve it, or even a proper way to perform it will be very much appreciated. i will happily provide any more details if needed

      if (number < 0) {
        return 0;
      }; 

      let numbersBelow = [];
        for (var i = 0; i <= number - 1; i  ) {
        numbersBelow.push(i);
      }; 
       
      let multiplesOfThree = [];
      let multiplesOfFive = [];
      for (var t = 0; t < numbersBelow.length; t  ){
     if (numbersBelow[t] % 3 === 0) {
       multiplesOfThree.push(numbersBelow[t]);
    } else if (numbersBelow[t] % 5 === 0) {
      multiplesOfFive.push(numbersBelow[t]);
    }
      }; 
   
      let intersectionResult = [];
      intersectionResult = multiplesOfFive.filter(x => multiplesOfThree.indexOf(x) !== -1);
     if (intersectionResult.length === 0) { intersectionResult = [0, 0]};
  
    const reducer = (accumulator, curr) => accumulator   curr; 
   
     return   multiplesOfThree.reduce(reducer)   multiplesOfFive.reduce(reducer)  - intersectionResult.reduce(reducer); 
   }

this is the error message when testing on code wars:

TypeError: Reduce of empty array with no initial value
    at Array.reduce (<anonymous>)
    at solution (/workspace/node/test.js:28:32)
    at test (/workspace/node/test.js:37:16)
    at Suite.<anonymous> (/workspace/node/test.js:51:3)
    at Object.create (/workspace/node/node_modules/.pnpm/[email protected]/node_modules/mocha/lib/interfaces/common.js:148:19)
    at context.describe.context.context (/workspace/node/node_modules/.pnpm/[email protected]/node_modules/mocha/lib/interfaces/bdd.js:42:27)
    at /workspace/node/test.js:49:1
    at Object.<anonymous> (/workspace/node/test.js:82:3)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:12)
    at ModuleWrap.<anonymous> (internal/modules/esm/translators.js:199:29)
    at ModuleJob.run (internal/modules/esm/module_job.js:183:25)
    at async Loader.import (internal/modules/esm/loader.js:178:24)
    at async formattedImport (/workspace/node/node_modules/.pnpm/[email protected]/node_modules/mocha/lib/nodejs/esm-utils.js:7:14)
    at async Object.exports.requireOrImport (/workspace/node/node_modules/.pnpm/[email protected]/node_modules/mocha/lib/nodejs/esm-utils.js:48:32)
    at async Object.exports.loadFilesAsync (/workspace/node/node_modules/.pnpm/[email protected]/node_modules/mocha/lib/nodejs/esm-utils.js:88:20)
    at async singleRun (/workspace/node/node_modules/.pnpm/[email protected]/node_modules/mocha/lib/cli/run-helpers.js:125:3)
    at async Object.exports.handler (/workspace/node/node_modules/.pnpm/[email protected]/node_modules/mocha/lib/cli/run.js:374:5)



CodePudding user response:

Maybe I missed something, but it seems to me that you are overcomplicating things. Just sum up everything below a number that is not 0 and a multiple of 3 or a multiple of 5.

document.addEventListener(`change`, handle);

function handle(evt) {
  if (evt.target.id === `startnr`) {
    return sumOfMultiples(evt.target.value);
  }
}

function sumOfMultiples(nr) {
  console.clear();
  let sum = 0;
  
  if (nr < 0) {
    return console.log(`number should be > 0`);
  }
  
  while (nr--) {
    if (nr > 0 && nr % 3 === 0 || nr % 5 === 0) {
      sum  = nr;
    }
  }
  console.log(sum);
}
<input type="number" id="startnr" value=10> start number

CodePudding user response:

if you put

multiplesOfThree.reduce(reducer, 0)   multiplesOfFive.reduce(reducer, 0)  - intersectionResult.reduce(reducer, 0)

in your code you should fix your error

but I think that the approach below is more appropriate

const multiplyAndSum = (upperLimit, dividends) =>
  Array.from({
    length: upperLimit - 1
  }, (_, i) => i   1)
  .filter(n => dividends.some(d => n % d === 0))
  .reduce((res, n) => res   n, 0)


console.log(multiplyAndSum(10, [3, 5]))
console.log(multiplyAndSum(-1, [3, 5]))

CodePudding user response:

A slightly different approach with two variables for multiples and a total value.

const
    sum = n => {
        if (n <= 0) return 0;

        let total = 0,
            three = 0,
            five = 0;
            
        while (three < n || five < n) {
            if (three === five) {
                total  = three;
                three  = 3;
                five  = 5;
                continue;
            }

            if (three < five && three < n) {
                total  = three;
                three  = 3;
                continue;
            }
            
            if (five < three && five < n) {
                total  = five;
                five  = 5;
            }
        }
        
        return total;
    }
    
console.log(sum(10));

  • Related