Hey guys! today while surfing I found a reference to the Project Euler website (https://projecteuler.net/) and I found it really really interesting.The questions are a combination of maths and computer programming.Some of the puzzles are easy to solve and others might take a longer time, but trust me it is a lot of fun!
By now, within an hour I have solved 3 Problems whilst doing other things. I have started this series to post solution of problems presented in Project Euler. In this post I will give you the solution of very first Problem of Project Euler that is https://projecteuler.net/problem=1

Problem statement:

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.

Solution:

public class MultipleOf3And5{
public static void main(String args[]){
int j=0;
for(int i=1;i<1000;i++){
if(i%3==0 || i%5==0)
j+=i;
}
System.out.println(j);
}
}

what is this code doing?

There is this loop which runs from 1 to 999 as per requirement(see problem statement; below 1000) , it checks all the numbers in between 1 and 1000 by checking their remainder after dividing them with 3 and 5.

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

If remainder is 0 after dividing it to 3 the number is the multiple of 3 else if it is 0 after dividing it to 5 the number is the multiple of 5. In both cases number is added to previous sum

j+=i;

where initial value of j is 0 then it adds multiples of 3 and 5. For understanding you can also write this statement as

j=j+i

now dry run this code,1 is the obvious case,
on second iteration i=2
Remainders of “2 divide by 3” and “2 divide by 5” are not equal to zero so this condition

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

would fail

and loop would forward to next iteration that is i=3

now 3/3=1 left 0 remainder, condition would be true and it would add 3 in 0 as j=0 and i=3 in this iteration, which will make j=3 and so on.

If the number after dividing by 3 and 5 does not produce remainder 0, it will not add up in sum and loop will be forwarded to next iteration.