Problem 1: Multiples of 3 and 5

*Difficulty: Easy

  • 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.

  • How to solve:

We can solve this problem by looping i from 3 (3 is the smallest multiples of 3) to 999 (below 1000), then check

if (i mod 3 equals 0  or  i mod  5 equals 0)

if the condition is true, then add i to sum (initialized with 0)

  • Implementation (Java):

public class Prob1 {

public static void main(String[] args) {

        int sum = 0;

        long cur = System.currentTimeMillis();

        for(int i = 3; i < 1000; ++i) {

                if(i % 3 == 0 || i % 5 ==0) {

                sum += i;

        }

        }

        System.out.println(sum);

        System.out.println(“Took “ + (System.currentTimeMillis()cur) + “ms”);

       }

}

Solution took 0ms

 

Advertisements