Monday, May 8, 2017

BigInteger - Size Matters

As numbers get larger, you need to consider storing those values where a 64 bit data type is not enough.  Working with large numbers are fun even if the operators do not work as excepted with small numbers.

Java provides classes like java.math.BigInteger or java.math.BigDecimal to handle large numbers, but it takes some time getting used to.  

You don't just add values by using the plus operator ( + ) , you call methods like add(), multiply(), divide(), subtract() methods.

Comparing values are also a challenge.  You really need to read the API in order to know what to expect. 

compareTo() method documentation - "Compares this BigInteger with the specified BigInteger. This method is provided in preference to individual methods for each of the six boolean comparison operators (<, ==, >, >=, !=, <=). The suggested idiom for performing these comparisons is: (x.compareTo(y) <op> 0), where <op> is one of the six comparison operators."

The code below demonstrates the for loop operations using BigInteger.


public class LargeNumbers{
    public static void main(String args[]){
        final java.math.BigInteger NUM=new java.math.BigInteger("10000000");
        //final java.math.BigInteger NUM=new java.math.BigInteger("100000000");
        //final java.math.BigInteger NUM=new java.math.BigInteger("1000000000");
        //System.out.println(NUM.bitCount());  //check to see how many bits are used in the number
        long time=System.currentTimeMillis();
        System.out.println(calc(NUM));
        System.out.printf("Time: %20s\n\n",(getTime(System.currentTimeMillis()-time)));
    }

    //iterative recursion
    public static java.math.BigInteger calc(java.math.BigInteger n) {
        java.math.BigInteger result =new java.math.BigInteger("1");
        for (java.math.BigInteger t=n; t.compareTo(new java.math.BigInteger("1")) != 0; t=t.subtract(new java.math.BigInteger("1")))
             result = result.add(t);

        return result;
    }

    private static String getTime(long millis){
        long second = (millis / 1000) % 60;
        long minute = (millis / (1000 * 60)) % 60;
        long hour = (millis / (1000 * 60 * 60)) % 24;
        return String.format("%02d:%02d:%02d:%04d", hour, minute, second, millis);
    }

}

No comments:

Post a Comment