0

Should add all the natural numbers below 1000 that are multiples of 3 or 5.

var sum = _.reduce( _.range(1, 1000), function(x, n) {
  if (n % 3 == 0 || n % 5 == 0) { return x+=n; }
}, 0);

I expect the output to be 233168 but I get NaN.

For some reason sum is not accepting the initialized value of 0. However if I preface this with var sum = 0; then it works and returns the proper output of 233168

Why doesn't it accept the initialized value?

2
  • 4
    What are you returning if the number is not a multiple of 3 or 5? Sep 12, 2015 at 19:33
  • Just FYI, you can sum the multiples in a sequential range without a loop. It can be done with math only.
    – user1106925
    Sep 12, 2015 at 20:03

1 Answer 1

4

The problem is the reducing function returns undefined when the conditional fails .. thus x evaluates to undefined (the last return value) in the subsequent invocation .. and undefined + a number is .. well, NaN.

Also, reduce is being used incorrectly; it should carry its own state. Compare it with:

var sum = _.reduce( _.range(1, 1000), function(x, n) {
  // Add n to the tally if it is a valid multiple..
  // (the returned value is used as the *next* value of x)
  if (n % 3 == 0 || n % 5 == 0) { return x + n; }
  // ..or simply return the current tally.
  else { return x; }
}, 0);

Note that the sum variable was not assigned from within the reducing function (it would have been overwritten by the outside assignment anyway). This keeps reduce a pure operation, not withstanding the occasional abuse of a mutable memo, truer to its functional roots.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.