6.2 Calculate multiples of 3 and 5

The problem

This is the first question in Euler Project:

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

Euler Project is a very good place to practice your programming. I would encourage you to try more questions in the archive. Most question might be too hard for you at this point. Don’t be discouraged.

The code

Integer sum = 0;
for(Integer i = 3; i < 1000; i++)
    if(Math.mod(i, 3) == 0 || Math.mod(i, 5) == 0) 
        sum += i;

System.debug('Sum is: ' + sum);

The result should be 233168.

As you can see, the code is not much more complicated than the last one. By understanding the concepts we have already learnt, we can actually resolve a lot of programming issues now!

Next Post

6.3 Calculate Fibonacci sequence

Subscribe to Sfdcinpractice

Subscribe to get the latest blogs and tutorials of sfdcinpractice. No spam, no trash, only the awesome posts from sfdcinpractice. 

Leave a Reply

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