"Find the sum of all the multiples of 3 or 5 below 1000"
I am having problems with understanding why the solution below still returns the correct result because x3, x5 and x15 use int after division. That means that the result of the division is always rounded down and the decimals are neglected.
When I tried to replace all 3 ints by doubles I got the wrong result.
The solution is based on the following observation:
1 + 2 + ... + n = n*(n+1)/2
public static void main(String[] args) {
int nr = 1000;
nr--;
int x3 = nr/3;
int x5 = nr/5;
int x15 = nr/15;
long sum1 = 3*x3*(x3+1);
long sum2 = 5*x5*(x5+1);
long sum3 = 15*x15*(x15+1);
long sum = (sum1+sum2-sum3)/2;
System.out.println(sum)
}