Reputation:
I am trying to do this exercise:
Write a program that asks the user for N and M and adds up the integers between N and M using the formula
SUM(N to M) = SUM( 1 to M ) - SUM( 1 to N-1 )
I can get this to work for positive numbers but not negative numbers.
static int method2(int n, int m) {
int sum = 0;
int sum2 = 0;
for (int i = 1; i <= m; i++) {
sum = sum + i;
}
for (int i = 1; i <= n - 1; i++) {
sum2 = sum2 + i;
}
System.out.println("sum: " + sum + ", sum2: " + sum2);
return sum = sum - sum2;
}
e.g.
n = -1
, m = 1
returns sum = 1
. n = -5
, m = 5
returns sum = 15
.n = 5
, m = -5
returns sum = -10
.
These should all return 0
.e.g.
n = -2
, m = 3
, returns sum = 6
.n = -2
, m = 4
, returns sum = 10
.The problem is with for (int i = 1; i <= n - 1; i++)
, specifically i <= n - 1
because when n-1 <= 0
this will not run. I just can't think of a way around it.
Upvotes: 0
Views: 125
Reputation: 2248
If you really have to use that formula you could use instead of:
for (int i = 1; i <= m; i++) {
the following code which changes the index either by 1 or by -1
for (int i = 1; i <= m; i+=(int)Math.signum(m-1+0.1)) {
(added 0.1 such that in case m is 1 the result is positive and not 0)
Ofc you should do the same for n.
Upvotes: 0
Reputation: 107
You could always check before if n < 0.
And then do another reverse loop for negative numbers.
e.g.
int sum = 0;
if(m < 0){
for(int i = 0; i >= m; i--) {
sum += i;
}
} else {
for (int i = 1; i <= m; i++) {
sum += i;
}
}
Upvotes: 0
Reputation: 1332
Your formula
SUM(N to M) = SUM( 1 to M ) - SUM( 1 to N-1 )
Doesn't really make sense for negative values. If you give that up you can make your program simpler. We very often start for
loops at 0 or 1 but that doesn't have to be the case. You could instead start your loop at a n which might be negative:
static int method2(int n, int m) {
int sum = 0;
for (int i = n; i <= m; i++) {
sum = sum + i;
}
System.out.println("sum: " + sum);
return sum;
}
Upvotes: 1