static final BigInteger ONE = BigInteger.valueOf(1);
static final BigInteger TWO = BigInteger.valueOf(2);
static final BigInteger THREE = BigInteger.valueOf(3);
public static Iterator
ArrayList
new ArrayList
if (num.compareTo(ONE) <= 0) { // num<=ONE means skip it
factors.add(num);
return factors.iterator();
}
BigInteger div = TWO; // divisor
BigInteger divsq = BigInteger.valueOf(4); // div squared
while (num.compareTo(divsq) >= 0) {
BigInteger[] res = num.divideAndRemainder(div);
if (res[1].signum() == 0) { // if remainder is zero
factors.add(div);
num = res[0];
} else { // try next divisor
if (div == TWO)
div = THREE;
else
div = div.add(TWO);
divsq = div.multiply(div);
}
}
if (!num.equals(ONE)) // leftover must be a factor
factors.add(num);
return factors.iterator();
}
The constants ONE, TWO, and THREE are used often, so we create objects for them once. If the number we are
factoring is less than or equal to one, we treat it as its own factor (BigInteger and BigDecimal
implement the Comparable interface described on page 574). After this validity test we perform the real
work of the method: testing potential divisors. If a divisor divides into the number evenly, it is a prime factor,
and we proceed with the result of the division to find more factors. We first try two, and then all odd numbers,
until we reach a divisor whose square is larger than the current number. You could optimize this method in
any number of ways, but it shows how to use some BigInteger functionality.
BigDecimal provides an arbitrary-precision signed decimal number consisting of an arbitrary-precision
integer and an int scale that says how many decimal places are to the right of the decimal point. The actual
precision required can be set through a MathContext object that is either associated with the
BigDecimal at construction time or passed as an argument to the actual operation being performed.
Decimal division and changing a number's scale require rounding, which you can specify on each operation or
through an associated MathContext object. You can require that rounding be up, down, toward zero, away
from zero, or toward the nearest value. You can also assert that no rounding will be necessary, in which case
ArithmeticException will be thrown if you are found to be wrong. The eight different rounding modes
are defined by the RoundingMode enum.
25.5. java.net The Network
The java.net package provides classes for working with network infrastructure, such as sockets, network
addresses, Uniform Resource Identifiers (URIs), and Uniform Resource Locators (URLs).