Reputation: 5
The issue I'm having is understanding this code when running the command: java Driver 1000000 its returning: sum(1000000) = 1784293664
and no matter how long i try to look at it i cant understand why and how the code is doing this im just wondering if anyone can provide any help in understanding what this code actually does to the number?
class Sum
{
private int sum;
public int get() {
return sum;
}
public void set(int sum) {
this.sum = sum;
}
}
class Summation implements Runnable
{
private int upper;
private Sum sumValue;
public Summation(int upper, Sum sumValue) {
this.upper = upper;
this.sumValue = sumValue;
}
public void run() {
int sum = 0;
for (int i = 0; i <= upper; i++)
sum += i;
sumValue.set(sum);
}
}
public class Driver
{
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Usage Driver <integer>");
System.exit(0);
}
if (Integer.parseInt(args[0]) < 0) {
System.err.println(args[0] + " must be >= 0");
System.exit(0);
}
// Create the shared object
Sum sumObject = new Sum();
int upper = Integer.parseInt(args[0]);
Thread worker = new Thread(new Summation(upper, sumObject));
worker.start();
try {
worker.join();
} catch (InterruptedException ie) { }
System.out.println("sum(" + upper + ") = " + sumObject.get());
}
}
Thanks in advance
Andrew
Upvotes: 0
Views: 290
Reputation: 178263
Summing the numbers 1 through 1 million:
(1 + 1000000) * 1000000 / 2 = 500000500000
This causes overflow in the int
you're using to hold the sum. The result is:
500000500000 (mod 2^32) = 1784293664
Use a long
to store the sum; it has a maximum value of 9223372036854775807
and can hold the sum.
Upvotes: 6