How to Solve Euler 1 in JavaScript Posted in Polyglotbits on 04 of Dec, 2015

The Euler 1 problem is fairly simple to solve. Most people intuitively know how to do it. Here is how I would do it in JavaScript.

Array.apply(null, Array(1000)).map(function (_, i) {return i;}).reduce(function(sum, cur) {if(cur%3==0 || cur%5==0)sum+=cur;return sum});

From left to right we do:

  • create an array of 1000 elements
  • insert the index of each element as it’s value (effectively giving us a list from 1 to 1000
  • reduce that array so that each value that are a multiple of either 3, 5 or both is added to running sum

More about JavaScript