Solution using IntStream
From Java 8 you can use the class IntStream
to do the loop loop work:
IntStream stream = IntStream.range(1, 1000);
The above code will generate a Stream
representing all integers between 1 and 1000. To get the sum of the values that are multiples of 3 or 5, just filter through the multiples of 3 or 5 and add them up:
long result = stream.filter(value -> (value % 3 == 0 || value % 5 == 0)).sum();
Thus, the value of result
shall be the sum of all multiples of 3 or 5 between 1 and 1000, 233.168.
See working on 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 get:
3 * (1 + 2 + 3 + 4 + ... + 331 + 332 + 333)
That is, the sum of all multiples of 3 between 1 and 1000 is the equivalent of three times the sum of all integers 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 integers between 1 and X is worth:
1 + 2 + 3 + 4 + ... + X = X*(X+1)/2
Generalizing, we have that the sum of all 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
Similarly, the sum of all multiples of 5, between 1 and 999, shall be:
S(n=5) = 5*(999/5)*(999/5 + 1)/2 = 99.500
However, the 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:
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
Which is the desired result. In Java we can do so:
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 on Ideone.
Within the two ties, switch to
somax += i + i;
within the first andsomaz += i + i;
– user28595
There was a change. Before it returned 16, now it is returning 20.
– Hardysec
Just a clarification. The objective of the program is to sum all multiples from 3 or 5 to 1000, correct?
– user28595
Or is the goal of the program to sum all multiples between "3 and 5" up to 1000? haha
– viana
"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."
– Hardysec
So it is 3 or 5. It’s because the way you wrote in the double interpretation question, as @acklay explained in his answer, and ends up generating a completely different answer.
– user28595
Thanks for the correction. I hadn’t noticed that.
– Hardysec