I am trying to make a problem of this page , and it came out as follows:
public static int metodo() {
int total = 0;
for (int i=1; i<1000; ++i) {
if (i%3 == 0 || i%5 == 0) { total += i; }
};
return total;
}
but I am trying not to use the remainder operator, and to obtain the multiples by multiplying by 5 or 3 in some way, but every time I do not try it, it does not give me the expected result, is there a way to do it through multiplication?
A posibility:
Explanation: We first add all the multiples of 3 and then those of 5. Then we subtract those that are multiples of both (so multiples of 15) to correct for the fact that we added these twice before.
In a way this is more of a math problem than a programming problem.
First we are going to calculate the sum of the numbers less than X that are multiples of a divisor D. We calculate the maximum multiple of D that is less than X, we call it M(X,D) : M(X,D) = ( ( X-1) integer_division D ) * D
In the case of divisor 3 : M(1000,3) = 999
We calculate the sum: 3 + 6 + ... + 996 + 999 ; which we call S(X,D)
This is an arithmetic progression , whose sum is given by:
Where :
That in java we calculate like this:
The final result is the sums of the multiples of 3 and 5 that are less than X, that is: S(1000.3)+S(1000.5)
But there is a problem, by doing the above we have added the multiples of 15 twice, to compensate we subtract them once: Final result = S(1000.3)+S(1000.5)-S(1000.15)
In java this is:
This form requires a constant execution time, whereas with a loop the time increases as X increases.
If you do the comparisons separately it is easier, I also did those problems and this code gave me the correct result.