Blog

In JavaScript, a Function to Add Numbers from 1 to 4 Million Using the Modulus Operator
Posted on June 11, 2015 in Algorithms, JavaScript by Matt Jennings

/*
Add numbers 1 through 4 million inclusive that are
divisible by 3 or 5 but NOT divisible by 3 AND 5
*/
function addNumbers() {
  var sum = 0;
  
  for(var i = 1; i < 40000001; i++) {
    
    if((i % 3 === 0 || i % 5 === 0) && !(i % 3 === 0 && i % 5 === 0)) {
    /* 
    Alternate line below because a number divisible by 3 and 5 is ALSO
    divisible by 15:

    if((i % 3 === 0 || i % 5 === 0) && !(i % 15 === 0)) {
    */

      sum += i;
    }
    
  }
  
  return sum;
}

console.log(addNumbers());

Leave a Reply