Пример работы с BigInteger в Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import static pro.java.util.Print.println; | |
import java.math.BigInteger; | |
import java.util.Random; | |
public class BigIntegerClass { | |
public static void main(String[] args) { | |
// Примеры работы с BigInteger | |
// создали BigInteger из строки представляющей число | |
BigInteger bi1 = new BigInteger("987654321"); | |
println("bi1 = " + bi1); | |
BigInteger bi2 = new BigInteger("-123456789"); | |
println("bi2 = " + bi2); | |
// создали BigInteger из строки представляющей двоичное число | |
BigInteger bi3 = new BigInteger("101", 2); | |
println("bi3 = " + bi3); | |
// Отрицательное значение заданное массивом byte | |
byte[] bytes = new byte[] { (byte) 0xFF, 0x00, 0x00 }; // -65536 | |
BigInteger bi4 = new BigInteger(bytes); | |
println("bi4 = " + bi4); | |
// Положительное значение заданное массивом byte | |
bytes = new byte[] { 0x1, 0x00, 0x00 }; // 65536 | |
BigInteger bi5 = new BigInteger(bytes); | |
println("bi5 = " + bi5); | |
// Задаем знак для BigInteger создаваемого из массива byte | |
byte[] barSign = { 5, 7 }; // 1287 | |
BigInteger bi6 = new BigInteger(barSign); | |
println("bi6 = " + bi6); | |
println("BigInteger(-1,barSign) = " + new BigInteger(-1, barSign)); | |
// Генерируем случайное число BitInteger | |
int bitLength = 8; // 8 bits (диапазон от 0 до 255) | |
Random rnd = new Random(); | |
int certainty = 5; // 1 - 1/2(5) certainty | |
BigInteger birnd1 = new BigInteger(bitLength, certainty, rnd); | |
BigInteger birnd2 = new BigInteger(bitLength, rnd); | |
println("birnd1 = " + birnd1); | |
println("birnd2 = " + birnd2); | |
// Создаем BigInteger из целочисленного литерала | |
BigInteger bi7 = BigInteger.valueOf(42); | |
println("bi7 = " + bi7); | |
println("BigInteger.ONE = " + BigInteger.ONE); | |
println("BigInteger.TEN = " + BigInteger.TEN); | |
println("BigInteger.ZERO = " + BigInteger.ZERO); | |
// Примеры арифметических операций с BigInteger | |
println("bi1+bi2 = " + (bi1.add(bi2))); // + | |
println("bi1 = " + bi1 + " bi2 = " + bi2); | |
BigInteger bi8 = bi5.subtract(bi3); // - | |
println("bi8 = " + bi8); | |
println("bi3*bi7 = " + (bi3.multiply(bi7))); // * | |
println("bi5/10 = " + (bi5.divide(BigInteger.TEN))); // / | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment