Biginteger in java examples

BigInteger Class in Java

BigInteger class is used for the mathematical operation which involves very big integer calculations that are outside the limit of all available primitive data types.

In this way, BigInteger class is very handy to use because of its large method library and it is also used a lot in competitive programming.
Now below is given a list of simple statements in primitive arithmetic and its analogous statement in terms of BigInteger objects.

Initialization is as follows:

A = BigInteger.valueOf(54); B = BigInteger.valueOf(37);

And for Integers available as strings you can initialize them as follows:

A = new BigInteger(“54”); B = new BigInteger(“123456789123456789”);

Some constants are also defined in BigInteger class for ease of initialization as follows:

A = BigInteger.ONE; // Other than this, available constant are BigInteger.ZERO // and BigInteger.TEN

Mathematical operations are as follows:

int c = a + b; BigInteger C = A.add(B);

Other similar functions are subtract(), multiply(), divide(), remainder(), but all these functions take BigInteger as their argument so if we want this operation with integers or string convert them to BigInteger before passing them to functions as shown below:

String str = “123456789”; BigInteger C = A.add(new BigInteger(str)); int val = 123456789; BigInteger C = A.add(BigInteger.valueOf(val));

Extraction of value from BigInteger is as follows:

int x = A.intValue(); // value should be in limit of int x long y = A.longValue(); // value should be in limit of long y String z = A.toString();
if (a < b) <>// For primitive int if (A.compareTo(B) < 0) <>// For BigInteger

Actually compareTo returns -1(less than), 0(Equal), 1(greater than) according to values. For equality we can also use:

if (A.equals(B)) <> // A is equal to B

Methods of BigInteger Class

Method Action Performed
add(BigInteger val) Returns a BigInteger whose value is (this + val).
abs() Returns a BigInteger whose value is the absolute value of this BigInteger.
and(BigInteger val) Returns a BigInteger whose value is (this & val).
andNot(BigInteger val) Returns a BigInteger whose value is (this & ~val).
bitCount() Returns the number of bits in the two’s complement representation of this BigInteger that differ from its sign bit.
bitLength() Returns the number of bits in the minimal two’s-complement representation of this BigInteger, excluding a sign bit.
byteValueExact() Converts this BigInteger to a byte, checking for lost information.
clearBit(int n) Returns a BigInteger whose value is equivalent to this BigInteger with the designated bit cleared.
compareTo(BigInteger val) Compares this BigInteger with the specified BigInteger.
divide(BigInteger val) Returns a BigInteger whose value is (this / val).
divideAndRemainder(BigInteger val) Returns an array of two BigIntegers containing (this / val) followed by (this % val).
doubleValue() Converts this BigInteger to a double.
equals(Object x) Compares this BigInteger with the specified Object for equality.
flipBit(int n) Returns a BigInteger whose value is equivalent to this BigInteger with the designated bit flipped.
floatValue() Converts this BigInteger to a float.
gcd(BigInteger val) Returns a BigInteger whose value is the greatest common divisor of abs(this) and abs(val).
getLowestSetBit() Returns the index of the rightmost (lowest-order) one bit in this BigInteger (the number of zero bits to the right of the rightmost one bit).
hashCode() Returns the hash code for this BigInteger.
intValue() Converts this BigInteger to an int.
intValueExact() Converts this BigInteger to an int, checking for lost information.
isProbablePrime(int certainty) Returns true if this BigInteger is probably prime, false if it’s definitely composite.
longValue() Converts this BigInteger to a long.
longValueExact() Converts this BigInteger to a long, checking for lost information.
max(BigInteger val) Returns the maximum of this BigInteger and val.
min(BigInteger val) Returns the minimum of this BigInteger and val.
mod(BigInteger m Returns a BigInteger whose value is (this mod m).
modInverse(BigInteger m) Returns a BigInteger whose value is (this-1 mod m).
modPow(BigInteger exponent, BigInteger m Returns a BigInteger whose value is (thisexponent mod m).
multiply(BigInteger val) Returns a BigInteger whose value is (this * val).
negate() Returns a BigInteger whose value is (-this).
nextProbablePrime() Returns the first integer greater than this BigInteger that is probably prime.
not() Returns a BigInteger whose value is (~this).
or(BigInteger val) Returns a BigInteger whose value is (this | val).
pow(int exponent) Returns a BigInteger whose value is (thisexponent).
probablePrime(int bitLength, Random rnd) Returns a positive BigInteger that is probably prime, with the specified bitLength.
remainder(BigInteger val) Returns a BigInteger whose value is (this % val).
setBit(int n) Returns a BigInteger whose value is equivalent to this BigInteger with the designated bit set.
shiftLeft(int n) Returns a BigInteger whose value is (this
shiftRight(int n) Returns a BigInteger whose value is (this >> n).
shortValueExact() Converts this BigInteger to a short, checking for lost information.
signum() Returns the signum function of this BigInteger.
sqrt() Returns the integer square root of this BigInteger.
sqrtAndRemainder() Returns an array of two BigIntegers containing the integer square root s of this and its remainder this – s*s, respectively.
subtract(BigInteger val) Returns a BigInteger whose value is (this – val).
testBit(int n) Returns true if and only if the designated bit is set.
toByteArray() Returns a byte array containing the two’s-complement representation of this BigInteger.
toString() Returns the decimal String representation of this BigInteger.
toString(int radix) Returns the string representation of this BigInteger in the given radix.
valueOf(long val) Returns a BigInteger whose value is equal to that of the specified long.
xor(BigInteger val) Returns a BigInteger whose value is (this ^ val).

Illustration:

Factorial of 100 contains 158 digits in it so we can’t store it in any primitive data type available. We can store as large an Integer as we want in it. There is no theoretical limit on the upper bound of the range because memory is allocated dynamically but practically as memory is limited you can store a number that has Integer.MAX_VALUE number of bits in it which should be sufficient to store mostly all large values.

Источник

Class BigInteger

Immutable arbitrary-precision integers. All operations behave as if BigIntegers were represented in two’s-complement notation (like Java’s primitive integer types). BigInteger provides analogues to all of Java’s primitive integer operators, and all relevant methods from java.lang.Math. Additionally, BigInteger provides operations for modular arithmetic, GCD calculation, primality testing, prime generation, bit manipulation, and a few other miscellaneous operations.

Semantics of arithmetic operations exactly mimic those of Java’s integer arithmetic operators, as defined in The Java Language Specification. For example, division by zero throws an ArithmeticException , and division of a negative by a positive yields a negative (or zero) remainder.

Semantics of shift operations extend those of Java’s shift operators to allow for negative shift distances. A right-shift with a negative shift distance results in a left shift, and vice-versa. The unsigned right shift operator ( >>> ) is omitted since this operation only makes sense for a fixed sized word and not for a representation conceptually having an infinite number of leading virtual sign bits.

Semantics of bitwise logical operations exactly mimic those of Java’s bitwise integer operators. The binary operators ( and , or , xor ) implicitly perform sign extension on the shorter of the two operands prior to performing the operation.

Comparison operations perform signed integer comparisons, analogous to those performed by Java’s relational and equality operators.

Modular arithmetic operations are provided to compute residues, perform exponentiation, and compute multiplicative inverses. These methods always return a non-negative result, between 0 and (modulus — 1) , inclusive.

Bit operations operate on a single bit of the two’s-complement representation of their operand. If necessary, the operand is sign-extended so that it contains the designated bit. None of the single-bit operations can produce a BigInteger with a different sign from the BigInteger being operated on, as they affect only a single bit, and the arbitrarily large abstraction provided by this class ensures that conceptually there are infinitely many «virtual sign bits» preceding each BigInteger.

For the sake of brevity and clarity, pseudo-code is used throughout the descriptions of BigInteger methods. The pseudo-code expression (i + j) is shorthand for «a BigInteger whose value is that of the BigInteger i plus that of the BigInteger j .» The pseudo-code expression (i == j) is shorthand for » true if and only if the BigInteger i represents the same value as the BigInteger j .» Other pseudo-code expressions are interpreted similarly.

All methods and constructors in this class throw NullPointerException when passed a null object reference for any input parameter. BigInteger must support values in the range -2 Integer.MAX_VALUE (exclusive) to +2 Integer.MAX_VALUE (exclusive) and may support values outside of that range. An ArithmeticException is thrown when a BigInteger constructor or method would generate a value outside of the supported range. The range of probable prime values is limited and may be less than the full supported positive range of BigInteger . The range must be at least 1 to 2 500000000 .

Источник

Class BigInteger

Immutable arbitrary-precision integers. All operations behave as if BigIntegers were represented in two’s-complement notation (like Java’s primitive integer types). BigInteger provides analogues to all of Java’s primitive integer operators, and all relevant methods from java.lang.Math. Additionally, BigInteger provides operations for modular arithmetic, GCD calculation, primality testing, prime generation, bit manipulation, and a few other miscellaneous operations.

Semantics of arithmetic operations exactly mimic those of Java’s integer arithmetic operators, as defined in The Java Language Specification. For example, division by zero throws an ArithmeticException , and division of a negative by a positive yields a negative (or zero) remainder.

Semantics of shift operations extend those of Java’s shift operators to allow for negative shift distances. A right-shift with a negative shift distance results in a left shift, and vice-versa. The unsigned right shift operator ( >>> ) is omitted since this operation only makes sense for a fixed sized word and not for a representation conceptually having an infinite number of leading virtual sign bits.

Semantics of bitwise logical operations exactly mimic those of Java’s bitwise integer operators. The binary operators ( and , or , xor ) implicitly perform sign extension on the shorter of the two operands prior to performing the operation.

Comparison operations perform signed integer comparisons, analogous to those performed by Java’s relational and equality operators.

Modular arithmetic operations are provided to compute residues, perform exponentiation, and compute multiplicative inverses. These methods always return a non-negative result, between 0 and (modulus — 1) , inclusive.

Bit operations operate on a single bit of the two’s-complement representation of their operand. If necessary, the operand is sign-extended so that it contains the designated bit. None of the single-bit operations can produce a BigInteger with a different sign from the BigInteger being operated on, as they affect only a single bit, and the arbitrarily large abstraction provided by this class ensures that conceptually there are infinitely many «virtual sign bits» preceding each BigInteger.

For the sake of brevity and clarity, pseudo-code is used throughout the descriptions of BigInteger methods. The pseudo-code expression (i + j) is shorthand for «a BigInteger whose value is that of the BigInteger i plus that of the BigInteger j .» The pseudo-code expression (i == j) is shorthand for » true if and only if the BigInteger i represents the same value as the BigInteger j .» Other pseudo-code expressions are interpreted similarly.

All methods and constructors in this class throw NullPointerException when passed a null object reference for any input parameter. BigInteger must support values in the range -2 Integer.MAX_VALUE (exclusive) to +2 Integer.MAX_VALUE (exclusive) and may support values outside of that range. An ArithmeticException is thrown when a BigInteger constructor or method would generate a value outside of the supported range. The range of probable prime values is limited and may be less than the full supported positive range of BigInteger . The range must be at least 1 to 2 500000000 .

Источник

Читайте также:  Collection package in java
Оцените статью