I am working on a Java method called evenSum that sums all even numbers between two integers, from and to, inclusive. The requirements specify that if from is greater than to, the method should return -1. For example, evenSum(4, 6) should return 10, evenSum(10, 15) should return 36, and evenSum(4, 4) should return 4.
Although the method works for many cases, it fails test 8 due to performance issues, taking too long to execute. The test output suggests that the loop conditions might be inefficient.
The method currently checks if from is odd and increments it to the next even number, then sums even numbers in a loop until it reaches to. I suspect the loop is not optimized, especially for larger ranges.
I would appreciate any suggestions for improving the efficiency of my code to prevent timing out during tests. Initially, I expected the method to calculate the sum correctly for various input ranges, including edge cases. While it passed the first seven tests, it failed test 8 unexpectedly, leading me to believe there may be an inefficiency in the loop.
my code:
public static long evenSum(int from, int to) {
if (from > to) {
return -1L;
}
if (from % 2 != 0) {
from++;
}
long sum = 0L;
int currentValue = from;
while (currentValue <= to) {
sum += currentValue;
currentValue += 2;
}
return sum;
}
Dimmms1114 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.