Pages

Wednesday, January 15, 2014

Playing with Big Integers using Java BigInteger

The BigInteger class in java.math package allows to perform arithmetic operations on large numbers which do not fit into the Java primitive data types. The BigInteger class is particularly useful in cryptography operations where large prime numbers play a pivotal role.

The following snippet, which calculates the smallest factor of an integer (not in the most efficient way) gives a simple demonstration of fundamentals of using BitInteger instances in a program.

A key point to remember is the immutable nature of BitInteger instances.

For example, the loop counter variable "i" used in this code does not get updated by the operation i.add(two). Instead, the value has to be assigned back to the variable "i". As a result a new instance will be created for each operation. This adds further penalty to the slow addition, division... operations (in comparison to primitive data types).

 
import java.math.BigInteger;

public class BigIntegerTest {

    private static BigInteger getSmallestFactor(BigInteger n) {
        BigInteger two = new BigInteger("2");
        if (n.mod(two).compareTo(BigInteger.ZERO) == 0) {
            return two;
        }

        for (BigInteger i = new BigInteger("3"); n.compareTo(i.multiply(i)) >= 0; i = i.add(two)) {
            if (n.mod(i).compareTo(BigInteger.ZERO) == 0) {
                return i;
            }
        }
        return n;
    }

    public static void main(String[] args) {
        BigInteger prime1 = new BigInteger("2147483647");
        BigInteger prime2 = new BigInteger("2147483659");
        BigInteger value = prime1.multiply(prime2);
        BigInteger factor = getSmallestFactor(value);
        System.out.println(factor.toString());
    }
} 

No comments:

Post a Comment