| author | Jaroslav Tulach <jtulach@netbeans.org> |
| Fri Aug 27 14:06:39 2010 +0200 | |
| changeset 365 | 0b7ec6ef8a72 |
| parent 210 | acf2c31e22d4 |
| permissions | -rw-r--r-- |
| jtulach@321 | 1 |
package org.apidesign.math; |
| jtulach@148 | 2 |
|
| jtulach@148 | 3 |
/** Class to simplify arithmetical operations, improved version to compute |
| jtulach@148 | 4 |
* the sum for ranges, but only if the virtual machine is configured to |
| jtulach@148 | 5 |
* run in incompatible mode. |
| jtulach@148 | 6 |
* |
| jtulach@148 | 7 |
* @author Jaroslav Tulach <jtulach@netbeans.org> |
| jtulach@148 | 8 |
* @version 2.0 |
| jtulach@148 | 9 |
*/ |
| jtulach@148 | 10 |
// BEGIN: design.composition.arith2.0.property |
| jtulach@148 | 11 |
public class Arithmetica {
|
| jtulach@148 | 12 |
public int sumTwo(int one, int second) {
|
| jtulach@148 | 13 |
return one + second; |
| jtulach@148 | 14 |
} |
| jtulach@148 | 15 |
|
| jtulach@148 | 16 |
public int sumAll(int... numbers) {
|
| jtulach@187 | 17 |
if (numbers.length == 0) {
|
| jtulach@187 | 18 |
return 0; |
| jtulach@187 | 19 |
} |
| jtulach@148 | 20 |
int sum = numbers[0]; |
| jtulach@148 | 21 |
for (int i = 1; i < numbers.length; i++) {
|
| jtulach@148 | 22 |
sum = sumTwo(sum, numbers[i]); |
| jtulach@148 | 23 |
} |
| jtulach@148 | 24 |
return sum; |
| jtulach@148 | 25 |
} |
| jtulach@148 | 26 |
|
| jtulach@148 | 27 |
public int sumRange(int from, int to) {
|
| jtulach@149 | 28 |
// BEGIN: design.composition.arith2.0.property.if |
| jtulach@148 | 29 |
if (Boolean.getBoolean("arithmetica.v2")) {
|
| jtulach@148 | 30 |
return sumRange2(from, to); |
| jtulach@148 | 31 |
} else {
|
| jtulach@148 | 32 |
return sumRange1(from, to); |
| jtulach@148 | 33 |
} |
| jtulach@149 | 34 |
// END: design.composition.arith2.0.property.if |
| jtulach@148 | 35 |
} |
| jtulach@148 | 36 |
|
| jtulach@148 | 37 |
private int sumRange1(int from, int to) {
|
| jtulach@148 | 38 |
int len = to - from; |
| jtulach@210 | 39 |
if (len < 0) {
|
| jtulach@210 | 40 |
len = -len; |
| jtulach@210 | 41 |
from = to; |
| jtulach@210 | 42 |
} |
| jtulach@148 | 43 |
int[] array = new int[len + 1]; |
| jtulach@148 | 44 |
for (int i = 0; i <= len; i++) {
|
| jtulach@148 | 45 |
array[i] = from + i; |
| jtulach@148 | 46 |
} |
| jtulach@148 | 47 |
return sumAll(array); |
| jtulach@148 | 48 |
} |
| jtulach@148 | 49 |
|
| jtulach@148 | 50 |
private int sumRange2(int from, int to) {
|
| jtulach@210 | 51 |
return (from + to) * (Math.abs(to - from) + 1) / 2; |
| jtulach@148 | 52 |
} |
| jtulach@152 | 53 |
} |
| jtulach@148 | 54 |
// END: design.composition.arith2.0.property |