Euler 1 – Java

Brute force approach

Question: 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.

Logic: The first part of the problem asks us to find the multiples of 3 & 5 under 1000. For this, we write a simple for loop starting from 3 and ending before 1000.
for(int x = 3; x < 1000; x++){}

Next we select all the values that are divisible by 3 and 5. We use the if statement and the %(modulus) operand to find the the remainder of each increment of x.
if(x % 3 == 0 || x % 5 == 0){}

Finally we take every value that passes the if check and add it upon itself.
int total = 0;
...
total += x;

Code:
//generate for loop going to 1000 starting from 3 and incrementing by 1
int total = 0;
for(int x=3; x<1000; x++){
//filter by multiples of 3 and 5
if(x%3 == 0 || x%5 == 0){
//add numbers filtered by if statement
total += x;
}
}
System.out.println("total sum is:" +total); //answer is 233168

Leave a Reply

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