Class BigInteger
- All Implemented Interfaces:
Serializable,Comparable<BigInteger>
public class BigInteger extends Number implements Comparable<BigInteger>, Serializable
Fast Cryptography
This implementation is efficient for operations traditionally used in cryptography, such as the generation of large prime numbers and computation of the modular inverse.Slow Two's Complement Bitwise Operations
This API includes operations for bitwise operations in two's complement representation. Two's complement is not the internal representation used by this implementation, so such methods may be inefficient. UseBitSet for high-performance bitwise operations on
arbitrarily-large sequences of bits.- See Also:
- Serialized Form
-
Field Summary
Fields Modifier and Type Field Description static BigIntegerONETheBigIntegerconstant 1.static BigIntegerTENTheBigIntegerconstant 10.static BigIntegerZEROTheBigIntegerconstant 0. -
Constructor Summary
Constructors Constructor Description BigInteger(byte[] value)Constructs a newBigIntegerfrom the given two's complement representation.BigInteger(int signum, byte[] magnitude)Constructs a newBigIntegerinstance with the given sign and magnitude.BigInteger(int bitLength, int certainty, Random random)Constructs a randomBigIntegerinstance in the range[0, pow(2, bitLength)-1]which is probably prime.BigInteger(int numBits, Random random)Constructs a random non-negativeBigIntegerinstance in the range[0, pow(2, numBits)-1].BigInteger(String value)Constructs a newBigIntegerby parsingvalue.BigInteger(String value, int radix)Constructs a newBigIntegerinstance by parsingvalue. -
Method Summary
Modifier and Type Method Description BigIntegerabs()Returns aBigIntegerwhose value is the absolute value ofthis.BigIntegeradd(BigInteger value)Returns aBigIntegerwhose value isthis + value.BigIntegerand(BigInteger value)Returns aBigIntegerwhose value isthis & value.BigIntegerandNot(BigInteger value)Returns aBigIntegerwhose value isthis & ~value.intbitCount()Returns the number of bits in the two's complement representation ofthiswhich differ from the sign bit.intbitLength()Returns the length of the value's two's complement representation without leading zeros for positive numbers / without leading ones for negative values.BigIntegerclearBit(int n)Returns aBigIntegerwhich has the same binary representation asthisbut with the bit at position n cleared.intcompareTo(BigInteger value)Compares thisBigIntegerwithvalue.BigIntegerdivide(BigInteger divisor)Returns aBigIntegerwhose value isthis / divisor.BigInteger[]divideAndRemainder(BigInteger divisor)Returns a two elementBigIntegerarray containingthis / divisorat index 0 andthis % divisorat index 1.doubledoubleValue()Returns thisBigIntegeras a double.booleanequals(Object x)Compares this instance with the specified object and indicates if they are equal.BigIntegerflipBit(int n)Returns aBigIntegerwhich has the same binary representation asthisbut with the bit at position n flipped.floatfloatValue()Returns thisBigIntegeras a float.BigIntegergcd(BigInteger value)Returns aBigIntegerwhose value is greatest common divisor ofthisandvalue.intgetLowestSetBit()Returns the position of the lowest set bit in the two's complement representation of thisBigInteger.inthashCode()Returns an integer hash code for this object.intintValue()Returns thisBigIntegeras an int value.booleanisProbablePrime(int certainty)Tests whether thisBigIntegeris probably prime.longlongValue()Returns thisBigIntegeras a long value.BigIntegermax(BigInteger value)Returns the maximum of thisBigIntegerandvalue.BigIntegermin(BigInteger value)Returns the minimum of thisBigIntegerandvalue.BigIntegermod(BigInteger m)Returns aBigIntegerwhose value isthis mod m.BigIntegermodInverse(BigInteger m)Returns aBigIntegerwhose value is1/this mod m.BigIntegermodPow(BigInteger exponent, BigInteger modulus)Returns aBigIntegerwhose value ispow(this, exponent) mod modulus.BigIntegermultiply(BigInteger value)Returns aBigIntegerwhose value isthis * value.BigIntegernegate()Returns aBigIntegerwhose value is the-this.BigIntegernextProbablePrime()Returns the smallest integer x >thiswhich is probably prime as aBigIntegerinstance.BigIntegernot()Returns aBigIntegerwhose value is~this.BigIntegeror(BigInteger value)Returns aBigIntegerwhose value isthis | value.BigIntegerpow(int exp)Returns aBigIntegerwhose value ispow(this, exp).static BigIntegerprobablePrime(int bitLength, Random random)Returns a random positiveBigIntegerinstance in the range[0, pow(2, bitLength)-1]which is probably prime.BigIntegerremainder(BigInteger divisor)Returns aBigIntegerwhose value isthis % divisor.BigIntegersetBit(int n)Returns aBigIntegerwhich has the same binary representation asthisbut with the bit at position n set.BigIntegershiftLeft(int n)Returns aBigIntegerwhose value isthis << n.BigIntegershiftRight(int n)Returns aBigIntegerwhose value isthis >> n.intsignum()Returns the sign of thisBigInteger.BigIntegersubtract(BigInteger value)Returns aBigIntegerwhose value isthis - value.booleantestBit(int n)Tests whether the bit at position n inthisis set.byte[]toByteArray()Returns the two's complement representation of thisBigIntegerin a byte array.StringtoString()Returns a string representation of thisBigIntegerin decimal form.StringtoString(int radix)Returns a string containing a string representation of thisBigIntegerwith base radix.static BigIntegervalueOf(long value)Returns aBigIntegerwhose value is equal tovalue.BigIntegerxor(BigInteger value)Returns aBigIntegerwhose value isthis ^ value.Methods inherited from class java.lang.Number
byteValue, shortValue
-
Field Details
-
ZERO
TheBigIntegerconstant 0. -
ONE
TheBigIntegerconstant 1. -
TEN
TheBigIntegerconstant 10.
-
-
Constructor Details
-
BigInteger
Constructs a random non-negativeBigIntegerinstance in the range[0, pow(2, numBits)-1].- Parameters:
numBits- maximum length of the newBigIntegerin bits.random- is the random number generator to be used.- Throws:
IllegalArgumentException- ifnumBits< 0.
-
BigInteger
Constructs a randomBigIntegerinstance in the range[0, pow(2, bitLength)-1]which is probably prime. The probability that the returnedBigIntegeris prime is greater than1 - 1/2<sup>certainty</sup>).Note: the
Randomargument is ignored ifbitLength >= 16, where this implementation will use OpenSSL'sBN_generate_prime_exas a source of cryptographically strong pseudo-random numbers.- Parameters:
bitLength- length of the newBigIntegerin bits.certainty- tolerated primality uncertainty.- Throws:
ArithmeticException- ifbitLength < 2.- See Also:
- Specification of random generator used from OpenSSL library
-
BigInteger
Constructs a newBigIntegerby parsingvalue. The string representation consists of an optional plus or minus sign followed by a non-empty sequence of decimal digits. Digits are interpreted as if byCharacter.digit(char,10).- Parameters:
value- string representation of the newBigInteger.- Throws:
NullPointerException- ifvalue == null.NumberFormatException- ifvalueis not a valid representation of aBigInteger.
-
BigInteger
Constructs a newBigIntegerinstance by parsingvalue. The string representation consists of an optional plus or minus sign followed by a non-empty sequence of digits in the specified radix. Digits are interpreted as if byCharacter.digit(char, radix).- Parameters:
value- string representation of the newBigInteger.radix- the base to be used for the conversion.- Throws:
NullPointerException- ifvalue == null.NumberFormatException- ifvalueis not a valid representation of aBigIntegeror ifradix < Character.MIN_RADIXorradix > Character.MAX_RADIX.
-
BigInteger
public BigInteger(int signum, byte[] magnitude)Constructs a newBigIntegerinstance with the given sign and magnitude.- Parameters:
signum- sign of the newBigInteger(-1 for negative, 0 for zero, 1 for positive).magnitude- magnitude of the newBigIntegerwith the most significant byte first.- Throws:
NullPointerException- ifmagnitude == null.NumberFormatException- if the sign is not one of -1, 0, 1 or if the sign is zero and the magnitude contains non-zero entries.
-
BigInteger
public BigInteger(byte[] value)Constructs a newBigIntegerfrom the given two's complement representation. The most significant byte is the entry at index 0. The most significant bit of this entry determines the sign of the newBigIntegerinstance. The array must be nonempty.- Parameters:
value- two's complement representation of the newBigInteger.- Throws:
NullPointerException- ifvalue == null.NumberFormatException- if the length ofvalueis zero.
-
-
Method Details
-
valueOf
Returns aBigIntegerwhose value is equal tovalue. -
toByteArray
public byte[] toByteArray()Returns the two's complement representation of thisBigIntegerin a byte array. -
abs
Returns aBigIntegerwhose value is the absolute value ofthis. -
negate
Returns aBigIntegerwhose value is the-this. -
add
Returns aBigIntegerwhose value isthis + value. -
subtract
Returns aBigIntegerwhose value isthis - value. -
signum
public int signum()Returns the sign of thisBigInteger.- Returns:
-1ifthis < 0,0ifthis == 0,1ifthis > 0.
-
shiftRight
Returns aBigIntegerwhose value isthis >> n. For negative arguments, the result is also negative. The shift distance may be negative which means thatthisis shifted left.Implementation Note: Usage of this method on negative values is not recommended as the current implementation is not efficient.
- Parameters:
n- shift distance- Returns:
this >> nifn >= 0;this << (-n)otherwise
-
shiftLeft
Returns aBigIntegerwhose value isthis << n. The result is equivalent tothis * pow(2, n)if n >= 0. The shift distance may be negative which means thatthisis shifted right. The result then corresponds tofloor(this / pow(2, -n)).Implementation Note: Usage of this method on negative values is not recommended as the current implementation is not efficient.
- Parameters:
n- shift distance.- Returns:
this << nifn >= 0;this >> (-n). otherwise
-
bitLength
public int bitLength()Returns the length of the value's two's complement representation without leading zeros for positive numbers / without leading ones for negative values.The two's complement representation of
thiswill be at leastbitLength() + 1bits long.The value will fit into an
intifbitLength() < 32or into alongifbitLength() < 64.- Returns:
- the length of the minimal two's complement representation for
thiswithout the sign bit.
-
testBit
public boolean testBit(int n)Tests whether the bit at position n inthisis set. The result is equivalent tothis & pow(2, n) != 0.Implementation Note: Usage of this method is not recommended as the current implementation is not efficient.
- Parameters:
n- position where the bit inthishas to be inspected.- Throws:
ArithmeticException- ifn < 0.
-
setBit
Returns aBigIntegerwhich has the same binary representation asthisbut with the bit at position n set. The result is equivalent tothis | pow(2, n).Implementation Note: Usage of this method is not recommended as the current implementation is not efficient.
- Parameters:
n- position where the bit inthishas to be set.- Throws:
ArithmeticException- ifn < 0.
-
clearBit
Returns aBigIntegerwhich has the same binary representation asthisbut with the bit at position n cleared. The result is equivalent tothis & ~pow(2, n).Implementation Note: Usage of this method is not recommended as the current implementation is not efficient.
- Parameters:
n- position where the bit inthishas to be cleared.- Throws:
ArithmeticException- ifn < 0.
-
flipBit
Returns aBigIntegerwhich has the same binary representation asthisbut with the bit at position n flipped. The result is equivalent tothis ^ pow(2, n).Implementation Note: Usage of this method is not recommended as the current implementation is not efficient.
- Parameters:
n- position where the bit inthishas to be flipped.- Throws:
ArithmeticException- ifn < 0.
-
getLowestSetBit
public int getLowestSetBit()Returns the position of the lowest set bit in the two's complement representation of thisBigInteger. If all bits are zero (this==0) then -1 is returned as result.Implementation Note: Usage of this method is not recommended as the current implementation is not efficient.
-
bitCount
public int bitCount()Returns the number of bits in the two's complement representation ofthiswhich differ from the sign bit. Ifthisis negative, the result is equivalent to the number of bits set in the two's complement representation of-this - 1.Use
bitLength(0)to find the length of the binary value in bits.Implementation Note: Usage of this method is not recommended as the current implementation is not efficient.
-
not
Returns aBigIntegerwhose value is~this. The result of this operation is-this-1.Implementation Note: Usage of this method is not recommended as the current implementation is not efficient.
-
and
Returns aBigIntegerwhose value isthis & value.Implementation Note: Usage of this method is not recommended as the current implementation is not efficient.
- Parameters:
value- value to be and'ed withthis.- Throws:
NullPointerException- ifvalue == null.
-
or
Returns aBigIntegerwhose value isthis | value.Implementation Note: Usage of this method is not recommended as the current implementation is not efficient.
- Parameters:
value- value to be or'ed withthis.- Throws:
NullPointerException- ifvalue == null.
-
xor
Returns aBigIntegerwhose value isthis ^ value.Implementation Note: Usage of this method is not recommended as the current implementation is not efficient.
- Parameters:
value- value to be xor'ed withthis- Throws:
NullPointerException- ifvalue == null
-
andNot
Returns aBigIntegerwhose value isthis & ~value. Evaluatingx.andNot(value)returns the same result asx.and(value.not()).Implementation Note: Usage of this method is not recommended as the current implementation is not efficient.
- Parameters:
value- value to be not'ed and then and'ed withthis.- Throws:
NullPointerException- ifvalue == null.
-
intValue
public int intValue()Returns thisBigIntegeras an int value. Ifthisis too big to be represented as an int, thenthis % (1 << 32)is returned. -
longValue
public long longValue()Returns thisBigIntegeras a long value. Ifthisis too big to be represented as a long, thenthis % pow(2, 64)is returned. -
floatValue
public float floatValue()Returns thisBigIntegeras a float. Ifthisis too big to be represented as a float, thenFloat.POSITIVE_INFINITYorFloat.NEGATIVE_INFINITYis returned. Note that not all integers in the range[-Float.MAX_VALUE, Float.MAX_VALUE]can be exactly represented as a float.- Specified by:
floatValuein classNumber- Returns:
- the primitive float value of this object.
-
doubleValue
public double doubleValue()Returns thisBigIntegeras a double. Ifthisis too big to be represented as a double, thenDouble.POSITIVE_INFINITYorDouble.NEGATIVE_INFINITYis returned. Note that not all integers in the range[-Double.MAX_VALUE, Double.MAX_VALUE]can be exactly represented as a double.- Specified by:
doubleValuein classNumber- Returns:
- the primitive double value of this object.
-
compareTo
Compares thisBigIntegerwithvalue. Returns-1ifthis < value,0ifthis == valueand1ifthis > value, .- Specified by:
compareToin interfaceComparable<BigInteger>- Parameters:
value- value to be compared withthis.- Returns:
- a negative integer if this instance is less than
another; a positive integer if this instance is greater thananother; 0 if this instance has the same order asanother. - Throws:
NullPointerException- ifvalue == null.
-
min
Returns the minimum of thisBigIntegerandvalue.- Parameters:
value- value to be used to compute the minimum withthis.- Throws:
NullPointerException- ifvalue == null.
-
max
Returns the maximum of thisBigIntegerandvalue.- Parameters:
value- value to be used to compute the maximum withthis- Throws:
NullPointerException- ifvalue == null
-
hashCode
public int hashCode()Description copied from class:ObjectReturns an integer hash code for this object. By contract, any two objects for whichObject.equals(java.lang.Object)returnstruemust return the same hash code value. This means that subclasses ofObjectusually override both methods or neither method.Note that hash values must not change over time unless information used in equals comparisons also changes.
See Writing a correct
hashCodemethod if you intend implementing your ownhashCodemethod.- Overrides:
hashCodein classObject- Returns:
- this object's hash code.
- See Also:
Object.equals(java.lang.Object)
-
equals
Description copied from class:ObjectCompares this instance with the specified object and indicates if they are equal. In order to be equal,omust represent the same object as this instance using a class-specific comparison. The general contract is that this comparison should be reflexive, symmetric, and transitive. Also, no object reference other than null is equal to null.The default implementation returns
trueonly ifthis == o. See Writing a correctequalsmethod if you intend implementing your ownequalsmethod.The general contract for the
equalsandObject.hashCode()methods is that ifequalsreturnstruefor any two objects, thenhashCode()must return the same value for these objects. This means that subclasses ofObjectusually override either both methods or neither of them.- Overrides:
equalsin classObject- Parameters:
x- the object to compare this instance with.- Returns:
trueif the specified object is equal to thisObject;falseotherwise.- See Also:
Object.hashCode()
-
toString
Returns a string representation of thisBigIntegerin decimal form. -
toString
Returns a string containing a string representation of thisBigIntegerwith base radix. Ifradix < Character.MIN_RADIXorradix > Character.MAX_RADIXthen a decimal representation is returned. The characters of the string representation are generated with methodCharacter.forDigit.- Parameters:
radix- base to be used for the string representation.
-
gcd
Returns aBigIntegerwhose value is greatest common divisor ofthisandvalue. Ifthis == 0andvalue == 0then zero is returned, otherwise the result is positive.- Parameters:
value- value with which the greatest common divisor is computed.- Throws:
NullPointerException- ifvalue == null.
-
multiply
Returns aBigIntegerwhose value isthis * value.- Throws:
NullPointerException- ifvalue == null.
-
pow
Returns aBigIntegerwhose value ispow(this, exp).- Throws:
ArithmeticException- ifexp < 0.
-
divideAndRemainder
Returns a two elementBigIntegerarray containingthis / divisorat index 0 andthis % divisorat index 1.- Parameters:
divisor- value by whichthisis divided.- Throws:
NullPointerException- ifdivisor == null.ArithmeticException- ifdivisor == 0.- See Also:
divide(java.math.BigInteger),remainder(java.math.BigInteger)
-
divide
Returns aBigIntegerwhose value isthis / divisor.- Parameters:
divisor- value by whichthisis divided.- Returns:
this / divisor.- Throws:
NullPointerException- ifdivisor == null.ArithmeticException- ifdivisor == 0.
-
remainder
Returns aBigIntegerwhose value isthis % divisor. Regarding signs this methods has the same behavior as the % operator on ints: the sign of the remainder is the same as the sign of this.- Parameters:
divisor- value by whichthisis divided.- Throws:
NullPointerException- ifdivisor == null.ArithmeticException- ifdivisor == 0.
-
modInverse
Returns aBigIntegerwhose value is1/this mod m. The modulusmmust be positive. The result is guaranteed to be in the interval[0, m)(0 inclusive, m exclusive). Ifthisis not relatively prime to m, then an exception is thrown.- Parameters:
m- the modulus.- Throws:
NullPointerException- ifm == nullArithmeticException- ifm < 0 orifthisis not relatively prime tom
-
modPow
Returns aBigIntegerwhose value ispow(this, exponent) mod modulus. The modulus must be positive. The result is guaranteed to be in the interval[0, modulus). If the exponent is negative, thenpow(this.modInverse(modulus), -exponent) mod modulusis computed. The inverse of this only exists ifthisis relatively prime to the modulus, otherwise an exception is thrown.- Throws:
NullPointerException- ifmodulus == nullorexponent == null.ArithmeticException- ifmodulus < 0or ifexponent < 0and not relatively prime tomodulus.
-
mod
Returns aBigIntegerwhose value isthis mod m. The modulusmmust be positive. The result is guaranteed to be in the interval[0, m)(0 inclusive, m exclusive). The behavior of this function is not equivalent to the behavior of the % operator defined for the built-inint's.- Parameters:
m- the modulus.- Returns:
this mod m.- Throws:
NullPointerException- ifm == null.ArithmeticException- ifm < 0.
-
isProbablePrime
public boolean isProbablePrime(int certainty)Tests whether thisBigIntegeris probably prime. Iftrueis returned, then this is prime with a probability greater than1 - 1/2<sup>certainty</sup>). Iffalseis returned, then this is definitely composite. If the argumentcertainty<= 0, then this method returns true.- Parameters:
certainty- tolerated primality uncertainty.- Returns:
true, ifthisis probably prime,falseotherwise.
-
nextProbablePrime
Returns the smallest integer x >thiswhich is probably prime as aBigIntegerinstance. The probability that the returnedBigIntegeris prime is greater than1 - 1/2<sup>100</sup>.- Returns:
- smallest integer >
thiswhich is probably prime. - Throws:
ArithmeticException- ifthis < 0.
-
probablePrime
Returns a random positiveBigIntegerinstance in the range[0, pow(2, bitLength)-1]which is probably prime. The probability that the returnedBigIntegeris prime is greater than1 - 1/2<sup>100</sup>).- Parameters:
bitLength- length of the newBigIntegerin bits.- Returns:
- probably prime random
BigIntegerinstance. - Throws:
IllegalArgumentException- ifbitLength < 2.
-