Project Euler : Problem 1 - Multiples of 3 and 5

2 minute read

Problem Statement : Multiples of 3 and 5

Problem 1 : If we list all the natural numbers below that are multiples of or , we get , , and . The sum of these multiples is .

Find the sum of all the multiples of or below .

Concept and Theory

The concept is straight forward from Set Theory and Arithmetic Progression.

image-center Venn_A_intersect_B

Lets say represents all the multiples of and represents all the multiples of . But there are some numbers like , , which are multiple of both and . We have to count them only once not twice.

So all that is left is just one thing, how to get the sum of all these multiples.

The answer is counting how many terms are there which are less than the given limit. From there its simple, the quotient of , and will give us the numbers of terms in the series of , and receptively. Exclude the last number if it happens to be a multiple of or or . Last term of the sequence can be calculated just by simply multiplying , or with corresponding number of terms in sequence.

We knows that the sum of any given Arithmetic Progression can be given as,

That’s it. Just plug in the numbers and you will have your answer.

Before you code : Keep in mind we don’t have to consider the last number so always subtract from whatever is given limit.

Code

/**
 * A function that returns the sum of all the unique multiples of 3 and 5 below
 * given input n.
 *
 * Note : We have to exclude the n if its a multiple of 3 or 5
 *
 * @param n
 *            : input range
 * @return : the sum
 */
static public long sumOfMultiplesOf3And5(long n) {
  long res = 0;

  n = n - 1;

  long numberOfTermsThreeSeries = n / 3;
  long maxMultipleOfThree = (numberOfTermsThreeSeries) * 3;

  long numberOfTermsFiveSeries = n / 5;
  long maxMultipleOfFive = (numberOfTermsFiveSeries) * 5;

  long numberOfTermsFifteenSeries = n / 15;
  long maxMultipleOfFifteen = (numberOfTermsFifteenSeries) * 15;

  long sumOfMultipleOfThree = ((numberOfTermsThreeSeries * (3 + maxMultipleOfThree)) / 2);
  long sumOfMultipleOfFive = ((numberOfTermsFiveSeries * (5 + maxMultipleOfFive)) / 2);
  long sumOfMultipleOfFifteen = ((numberOfTermsFifteenSeries * (15 + maxMultipleOfFifteen)) / 2);

  res = sumOfMultipleOfThree + sumOfMultipleOfFive - sumOfMultipleOfFifteen;

  return res;
}

Test Your Skills

Wanna try a harder version of the above problem ? Check this HackerRank problem.

Solution

The solution will remain same as above method , you just need to call it for each test case.

References and Further Readings

Leave a Comment

Your email address will not be published. Required fields are marked *

Loading...