Java Reference
In-Depth Information
25.4. java.math Mathematics
The package java.math is destined for classes that help with mathematical
calculations. Currently, it has three classes BigInteger , BigDecimal and
MathContext and an enum, RoundingMode , that defines different rounding
modes.
The class BigInteger provides arbitrary-precision integer arithmetic,
providing analogous operations for all integer operations except >>> ,
which is equivalent to >> because there is no sign bit to copy in an
arbitrary-precision integer. Neither will the provided single-bit operations
( clearBit and setBit ) change the sign of the number on which they oper-
ate. BigInteger behaves as if it were defined in two's-complement nota-
tionthe same notation used by the primitive integer types. Binary bit-
wise operations start by extending the sign of the smaller number and
then executing the operation, just as operations on primitive values do.
BigInteger objects are immutable, so all operations on them produce new
BigInteger objects. The following simple method returns an iterator over
the prime factors of a number:
static final BigInteger ONE = BigInteger.valueOf(1);
static final BigInteger TWO = BigInteger.valueOf(2);
static final BigInteger THREE = BigInteger.valueOf(3);
public static Iterator<BigInteger> factors(BigInteger num) {
ArrayList<BigInteger> factors =
new ArrayList<BigInteger>();
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);
 
Search WWH ::




Custom Search