3 /** Class to simplify arithmetical operations, improved version to compute
4 * the sum for ranges, but only if one uses the new constructor to indicate
5 * need for new version.
7 * @author Jaroslav Tulach <jtulach@netbeans.org>
10 // BEGIN: design.composition.arith2.0.compat
11 public class Arithmetica {
12 private final int version;
14 public Arithmetica() {
17 public Arithmetica(int version) {
18 this.version = version;
21 public int sumTwo(int one, int second) {
25 public int sumAll(int... numbers) {
26 if (numbers.length == 0) {
30 for (int i = 1; i < numbers.length; i++) {
31 sum = sumTwo(sum, numbers[i]);
36 public int sumRange(int from, int to) {
38 case 1: return sumRange1(from, to);
39 case 2: return sumRange2(from, to);
40 default: throw new IllegalStateException();
44 private int sumRange1(int from, int to) {
50 int[] array = new int[len + 1];
51 for (int i = 0; i <= len; i++) {
57 private int sumRange2(int from, int to) {
58 return (from + to) * (Math.abs(to - from) + 1) / 2;
61 // END: design.composition.arith2.0.compat