class - I'm having problems understanding how this Java works with the arguments I'm feeding it -
the issue i'm having understanding code when running command: java driver 1000000 returning: sum(1000000) = 1784293664
and no matter how long try @ cant understand why , how code doing im wondering if can provide in understanding code 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; (int = 0; <= 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 >= 0"); system.exit(0); } // create 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
summing numbers 1 through 1 million:
(1 + 1000000) * 1000000 / 2 = 500000500000
this causes overflow in int
you're using hold sum. result is:
500000500000 (mod 2^32) = 1784293664
use long
store sum; has maximum value of 9223372036854775807
, can hold sum.
Comments
Post a Comment