I know this is the Java section but still I would share my code in Python
Code:
sum(i for i in range(1000) if i % 3 == 0 or i % 5 == 0)
But the above is a bruteforce way. What if I tell you I can save about 400 loop cycles ?
Think Logically and a bit mathematically as well.
How many multiple of 3 are present within 1000 --> int(999 / 3) = 333 i.e {3, 6, ... 15, ... 30, ... 999)
How many multiple of 5 are present within 1000 --> int(995 / 5) = 199 i.e. {5, 10, ... 15... 25, 30, ... 995}
Now subtract the number of common multiples that is 15. So, how many multiples of 15 are present ? ---> 66.
Now all of these are in A.P series. So what you can do is calculate the sum of these AP series and get the result.
The Formula for Sum of A.P. Series (3 variations are there but I will use a only one)
Sum_N_Terms = N * (A + L) / 2
where N = No of terms, A = First Term, L = Last term
Therefore the complete workout would be :-
{333 * (3 + 999) / 2} + {199 * (5 + 995) / 2} - {66 * (15 + 990) / 2} = 233168
Pretty Easy
Now how is it an improvisation ?
The Bruteforce way would be to loop from 1 - 999 and check for multiplicity of 3 and 5 and then add. So the loop run for 999 times. But in the second case its just -> 333 + 199 + 66 = 598
So 401 loop cycles are saved.
Improvised Python Code
Code:
sum(i for i in range(3, 1000, 3)) + sum(i for i in range(5, 996, 5)) - sum(i for i in range(15, 991, 15))