Java Reference
In-Depth Information
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
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 con-
sisting 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 ar-
gument 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