I am doing a maths challenge for project euler and i have come across a strange problem when running the program. The result should be the sum of all the odd numbers up to 10,000,000 but i get a negative number, what am i doing wrong?
package program;
import java.util.*;
public class MainClass {
/**
* @param args
*/
public static void main(String[] args) {
int total = 0;
for (int counter = 1; counter < 10000000; counter++) {
if (!((counter % 2) == 0)) {
total+=counter;
}
}
System.out.println(total);
}
}
Use a
longinstead of anint. You’re getting a negative number due to integer overflow.