samples/composition/src-api2.0-property/org/apidesign/math/Arithmetica.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Thu, 30 Oct 2014 21:30:10 +0100
changeset 409 40cabcdcd2be
parent 210 acf2c31e22d4
permissions -rw-r--r--
Updating to NBMs from NetBeans 8.0.1 as some of them are required to run on JDK8
     1 package org.apidesign.math;
     2 
     3 /** Class to simplify arithmetical operations, improved version to compute
     4  * the sum for ranges, but only if the virtual machine is configured to
     5  * run in incompatible mode.
     6  *
     7  * @author Jaroslav Tulach <jtulach@netbeans.org>
     8  * @version 2.0
     9  */
    10 // BEGIN: design.composition.arith2.0.property
    11 public class Arithmetica {
    12     public int sumTwo(int one, int second) {
    13         return one + second;
    14     }
    15     
    16     public int sumAll(int... numbers) {
    17         if (numbers.length == 0) {
    18             return 0;
    19         }
    20         int sum = numbers[0];
    21         for (int i = 1; i < numbers.length; i++) {
    22             sum = sumTwo(sum, numbers[i]);
    23         }
    24         return sum;
    25     }
    26     
    27     public int sumRange(int from, int to) {
    28         // BEGIN: design.composition.arith2.0.property.if
    29         if (Boolean.getBoolean("arithmetica.v2")) {
    30             return sumRange2(from, to);
    31         } else {
    32             return sumRange1(from, to);
    33         }
    34         // END: design.composition.arith2.0.property.if
    35     }
    36 
    37     private int sumRange1(int from, int to) {
    38         int len = to - from;
    39         if (len < 0) {
    40             len = -len;
    41             from = to;
    42         }
    43         int[] array = new int[len + 1];
    44         for (int i = 0; i <= len; i++) {
    45             array[i] = from + i;
    46         }
    47         return sumAll(array);
    48     }
    49     
    50     private int sumRange2(int from, int to) {
    51         return (from + to) * (Math.abs(to - from) + 1) / 2;
    52     }
    53 }
    54 // END: design.composition.arith2.0.property