Hello, I am new to programming and I am trying to write a small program where it will calculate the sum for first N numbers. The problem is it does not work for even numbers. I have not managed to figure out why. My code is as follow:
int n = Integer.parseInt(args[0]);
int sum = (1+n)/2*n;
System.out.println(sum + " is the sum of first " + n + " numbers");
It doesn't work for even n because (n+1)/2
is truncated to an int.
This means that if, for example, n=4
, (n+1)/2
results in 2 instead of 2.5, so when you multiply it by n, you get 8 instead of the desired 10.
You can overcome this problem simply by changing the order of the operations. If you first multiply n by (n+1), the result is guaranteed to be even, so dividing it by 2 will produce the correct answer.
int sum = n*(1+n)/2;
You have integer division with (1+n)/2
. If your number is even, then (1+n)
is odd and the division by 2
will truncate any decimal result, so that an int
divided by an int
is still an int
.
Multiply by n
first, then divide by 2
. This ensures that the product is even before dividing, so the result is correct.
int sum = (1+n) * n / 2;
One can use ((n * (n + 1)) / 2)
. But I think the following will work without overflow errors for a few additional values of n
:
if ((n & 1) == 0) {
sum = ((n >> 1) * (n + 1));
} else {
sum = (n * ((n + 1) >> 1));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.