Skip to content

Instantly share code, notes, and snippets.

@systemist
Created February 4, 2015 15:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save systemist/f76ea0ad1051b0c5b077 to your computer and use it in GitHub Desktop.
Save systemist/f76ea0ad1051b0c5b077 to your computer and use it in GitHub Desktop.
// Adds all the natural numbers below `end` that are multiples of any of the
// values in `multiples`
//
// end - The Number that is the upper limit
// multiples - An Array of Numbers that will be checked for divisibility
//
// Examples
//
// multiples(1000, [3, 5])
// // => 233168
//
// Returns the Number sum of the multiples (see description)
function multiples(end, multiples) {
// create an array of number starting at 0 and ending at `end`
var range = _.range(end);
// filter the array to only contain numbers that are multiples of the numbers in `multiples`
var filtered = _.filter(range, function(i) {
// return true if i is divisible by any of the numbers in multiples
return _.any(multiples, function(mult) {
// return true if i is divisible by `mult`
return i % mult === 0;
});
});
// sum the numbers and return the result
return _.reduce(filtered, function(a, b) {
return a + b;
});
}
console.assert( multiples(1000, [3, 5]) === 233168 );
console.log("multiples: Success");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment