In a way this is a math problem rather than a programming one.
First let's calculate the sum of the numbers smaller 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 divider 3: M (1000,3) = 999
We calculate the sum: 3 + 6 + ... + 996 + 999; which we call S (X, D)
This is a arithmetic progression , the sum of which is given by:
- a1 = D
- an = M (X, D)
- n = M (X, D) / D
That in java we calculate like this:
// Calcular S(X,D)
public static int sumaMultiplosMenores( int maximo, int divisor )
int maxMultiplo = ((maximo-1)/divisor)*divisor; // M(X,D)
int numTerminos = maxMultiplo/divisor; // n
return numTerminos*(maxMultiplo+divisor)/2; // S(X,D)
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, in doing the above we have added the multiples of 15 twice, to compensate for the subtractions once: Final result = S (1000.3) + S (1000.5) -S (1000.15) )
In java this is:
public static int metodo()
return sumaMultiplosMenores(1000, 3) +
sumaMultiplosMenores(1000, 5) -
This form requires a constant execution time, while with a loop the time increases as X increases.