jtulach@148: package api; jtulach@148: jtulach@148: /** Class to simplify arithmetical operations, improved version to compute jtulach@148: * the sum for ranges, but only if the virtual machine is configured to jtulach@148: * run in incompatible mode. jtulach@148: * jtulach@148: * @author Jaroslav Tulach jtulach@148: * @version 2.0 jtulach@148: */ jtulach@148: // BEGIN: design.composition.arith2.0.property jtulach@148: public class Arithmetica { jtulach@148: public int sumTwo(int one, int second) { jtulach@148: return one + second; jtulach@148: } jtulach@148: jtulach@148: public int sumAll(int... numbers) { jtulach@187: if (numbers.length == 0) { jtulach@187: return 0; jtulach@187: } jtulach@148: int sum = numbers[0]; jtulach@148: for (int i = 1; i < numbers.length; i++) { jtulach@148: sum = sumTwo(sum, numbers[i]); jtulach@148: } jtulach@148: return sum; jtulach@148: } jtulach@148: jtulach@148: public int sumRange(int from, int to) { jtulach@149: // BEGIN: design.composition.arith2.0.property.if jtulach@148: if (Boolean.getBoolean("arithmetica.v2")) { jtulach@148: return sumRange2(from, to); jtulach@148: } else { jtulach@148: return sumRange1(from, to); jtulach@148: } jtulach@149: // END: design.composition.arith2.0.property.if jtulach@148: } jtulach@148: jtulach@148: private int sumRange1(int from, int to) { jtulach@148: int len = to - from; jtulach@210: if (len < 0) { jtulach@210: len = -len; jtulach@210: from = to; jtulach@210: } jtulach@148: int[] array = new int[len + 1]; jtulach@148: for (int i = 0; i <= len; i++) { jtulach@148: array[i] = from + i; jtulach@148: } jtulach@148: return sumAll(array); jtulach@148: } jtulach@148: jtulach@148: private int sumRange2(int from, int to) { jtulach@210: return (from + to) * (Math.abs(to - from) + 1) / 2; jtulach@148: } jtulach@152: } jtulach@148: // END: design.composition.arith2.0.property