Solution using IntStream
From Java 8 you can use the IntStream
class to do the loop job:
IntStream stream = IntStream.range(1, 1000);
The above code will generate a Stream
that represents all integers between 1 and 1000. To get the sum of the values that are multiples of 3 or 5, simply filter through the multiples of 3 or 5 and add them: / p>
long result = stream.filter(value -> (value % 3 == 0 || value % 5 == 0)).sum();
In this way, the value of result
will be the sum of all multiples of 3 or 5 between 1 and 1000, 233,168.
See working at Ideone .
Mathematical solution ❤️
Another possible solution is to analyze the problem mathematically. If we consider the sum of all values that are multiples of 3, we have:
3 + 6 + 9 + 12 + ... + 993 + 996 + 999
If we put the term 3 in evidence, we have:
3 * (1 + 2 + 3 + 4 + ... + 331 + 332 + 333)
That is, the sum of all multiples of 3 between 1 and 1000 is the triple equivalent of the sum of all integer values between 1 and 333, where 333 refers to the largest multiple of 3, less than 1000, divided by 3. And it is known that the sum of the integers between 1 and X is:
1 + 2 + 3 + 4 + ... + X = X*(X+1)/2
Generalizing, we have that the sum of all the multiples of n, between 1 and N, will be:
S(n) = n*(N/n)*(N/n + 1)/2
Therefore, the sum of all multiples of 3, between 1 and 999, will be:
S(n=3) = 3*(999/3)*(999/3 + 1)/2 = 166.833
Likewise, the sum of all multiples of 5, between 1 and 999, will be:
S(n=5) = 5*(999/5)*(999/5 + 1)/2 = 99.500
However, multiples of 15, which are multiples of 3 and 5, will be counted twice and, to obtain the desired value, one must subtract the sum of the multiples of 15, between 1 and 999: / p>
S(n=15) = 15*(999/15)*(999/15 + 1)/2 = 33.165
Thus, the sum of all multiples of 3 or 5, between 1 and 999, will be:
S = 166.833 + 99.500 - 33.165
S = 233.168
What is the desired result. In Java we can do this:
class Main {
public static void main(String[] args) {
int N = 1000;
int result = sum(3, N-1) + sum(5, N-1) - sum(15, N-1);
System.out.println(result);
}
public static int sum(int n, int N) {
return n * (N/n) * (N/n + 1)/2;
}
}
See working at Ideone .