DEV Community

Discussion on: Resource recommendation to help with deriving mathematical formulas

Collapse
 
afranco20 profile image
Alexander Franco • Edited

Both of these problems require some background knowledge of summations. You can read more about common summations formulas here.

Also, your solution for the first problem is incorrect. This problem is a bit tricky as it requires the use of the inclusion–exclusion principle in order to prevent counting multiples of 15 twice. This stack exchange answer shows the formula used in this solution.

The correct solution for problem #1 would be as follows

function sum(factor, max) {
  let n;

  if (max % factor == 0) {
    // we must subtract 1 to find  the
    // number of factors UNDER our max
    n = (max / factor) - 1;
  } else {
    // we need a whole number for the
    // upper limit of our summation
    n = Math.floor(max / factor);
  }

  // formula: c * sum i from i = 1 to k
  return factor * ((n * (n + 1)) / 2);
}

const a = sum(3, 1000);  // sum of multiples of 3
const b = sum(5, 1000);  // sum of multiples of 5
const c = sum(15, 1000); // intersection

// we must subtract the intersection because
// we would be counting multiples of 15 twice
console.log(a + b - c);  // result: 233168
Collapse
 
lilyyanglt profile image
Lily

Hello Alexander!!! Thank you so much the reply!!!! No wonder I couldn't get the answer right for the first problem, but I was confused because it worked when the max was 10! I will read up on all the links you provided and get a better understanding on how to solve these types of problems!

Thank you thank you!!