Project Euler 1: Multiples of 3 and 5

Project Euler 1 - Multiples of 3 and 5

Problem

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6, and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

Official Problem

Solution Approach

In this problem, we have to find the sum of elements of 3 or 5 which are less than 1000. The solution is pretty straightforward. You can apply a single loop over the multiples of the given numbers which will do the trick.

The catch here is if we take the multiples of 3 and multiples of 5 separately then we have to handle the cases of 15, 30, 45 …. Separately as they are both the multiples of 3 as well as 5, hence it’s better to take the two conditions together using an β€˜or’ condition which will take multiples of 15 only once and hence our problem is solved. 

Coming to the code part of the solution, first, initialize the two variables sum as 0 and limit as 1000 as given in the question. Then we iterate from 3 to the limit and use or condition to check if the element is divisible by either 3 or 5 or not. If it is divisible then we just add that element to the sum and return that as the answer.

Video Solution

Solution Code

Python Solution

Java Solution


For more Project Euler explained solutions visit Project Euler Detailed Solutions.

For Leetcode detailed solutions go to Leetcode Detailed Solutions.

If you like capture the flag challenges visit here.

Check out my socials below in the footer. Feel free to ask any doubts in the comment section or contact me via the Contact page I will surely respond. Happy Coding πŸ™‚

Leave a Comment

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