Java 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 .
Field Summary
Constructor Summary
Translates a byte array containing the two’s-complement binary representation of a BigInteger into a BigInteger.
Translates a byte sub-array containing the two’s-complement binary representation of a BigInteger into a BigInteger.
Constructs a randomly generated positive BigInteger that is probably prime, with the specified bitLength.
Constructs a randomly generated BigInteger, uniformly distributed over the range 0 to (2 numBits — 1), inclusive.
Method Summary
Returns the number of bits in the two’s complement representation of this BigInteger that differ from its sign bit.
Returns the number of bits in the minimal two’s-complement representation of this BigInteger, excluding a sign bit.
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).
Returns an array of two BigIntegers containing the integer square root s of this and its remainder this — s*s , respectively.
Java biginteger целочисленное деление
Встроенные примитивные числовые типы не всегда могут подходить для определенных программ. Например, необходимо хранить и использовать в программе очень большие числа, которые выходят за пределы допустимых значений для типов long и double. В этом случае для работы с числовыми данными можно использовать два дополнительных типа из пакета java.math — BigInteger (для целочисленных данных) и BigDecimal (для чисел с плавающей точкой).
Основные методы класса BigInteger:
- BigInteger add(BigInteger other) : возвращает сумму двух чисел
- BigInteger subtract(BigInteger other) : возвращает разность двух чисел
- BigInteger multiply(BigInteger other) : возвращает произведение двух чисел
- BigInteger divide(BigInteger other) : возвращает частное двух чисел
- BigInteger mod(BigInteger other) : возвращает остаток от целочисленного деления двух чисел
- BigInteger sqrt() : возвращает квадратный корень числа
- int compareTo(BigInteger other) : сравнивает два числа. Возвращает -1, если текущий объект меньше числа other, 1 — если текущий объект больше и 0 — если числа равны
- static BigInteger valueOf(long x) : возвращает объект BigInteger, значение которого равно числу, переданному в качестве параметра
- int intValue() : конвертирует объект BigInteger в объект int
- byte byteValue() : преобразует объект BigInteger в byte
- short shortValue() : преобразует объект BigInteger в short
- long longValue() : преобразует объект BigInteger в long
Основные методы класса BigDecimal:
- BigDecimal add(BigDecimal other) : возвращает сумму двух чисел
- BigDecimal subtract(BigDecimal other) : возвращает разность двух чисел
- BigDecimal multiply(BigDecimal other) : возвращает произведение двух чисел
- BigDecimal divide(BigDecimal other) : возвращает частное двух чисел
- BigDecimal divide(BigDecimal other, RoundingMode mode) : результат деления двух чисел, округленное в соответствии с режимом mode
- int compareTo(BigDecimal other) : сравнивает два числа. Возвращает -1, если текущий объект меньше числа other, 1 — если текущий объект больше и 0 — если числа равны
- static BigDecimal valueOf(double x) : возвращает объект BigDecimal, значение которого равно числу, переданному в качестве параметра
- double doubleValue() : преобразует объект BigDecimal в double
- float floatValue() : преобразует объект BigDecimal в float
Пример использования классов BigInteger и BigDecimal:
import java.math.*; public class Program < public static void main(String[] args) < BigInteger a = BigInteger.valueOf(2147483647); BigInteger b = BigInteger.valueOf(2147483641); //a = a * b; // так нельзя a = a.multiply(b); System.out.println(a); // 4611686001247518727 long x = a.longValue(); System.out.println(x); // 4611686001247518727 BigDecimal c = BigDecimal.valueOf(2325.06); BigDecimal d = BigDecimal.valueOf(215.06); c = c.subtract(d.multiply(BigDecimal.valueOf(2.1))); System.out.println(c); // 1873.434 double y = c.doubleValue(); System.out.println(y); // 1873.434 >>
Стоит отметить, несмотря на то, что объекты BigInteger и BigDecimal представляют числа, мы не можем применять с ними стандартные арифметические операции. Все математические действия с данными объектами идут через их методы.
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 .