Java - Looping Through A Range of BigInteger Values

Recently, I was just coding something and came across a situation, where I'd to loop through a range of BigInteger values. I'd to think a bit to work on this, as I haven't worked extensively on arbitrary precision arithmetic. Below is an example of how to loop through a range of BigInteger values:


3 comments:

  1. Hey, Did you get any solution for above situation?

    ReplyDelete
    Replies
    1. Hello there..What solution are you talking about?

      Delete
  2. I ran below code -
    BigInteger i = new BigInteger("0");
    BigInteger size = new BigInteger("184467440730000");
    //List s = new ArrayList();
    Stack s = new Stack();
    long start = System.currentTimeMillis();
    System.out.println(start);
    for (;i.compareTo(size) <= 0; i = i.add(BigInteger.valueOf(1))) {
    //s.add("s");
    s.push(i);
    //System.out.println(i);
    }
    long end = System.currentTimeMillis();
    System.out.println(end);
    System.out.println(end - start);

    It gives me below exception -
    1358827560521
    Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at java.math.BigInteger.add(BigInteger.java:1048)
    at javasa.Test.main(Test.java:103)

    I was planning to use the BigInteger datatype for storing the size of pool which can be a very large number. And I might need to iterate through that pool objects, so I wrote this code, however it does not seem efficient.

    ReplyDelete

Note: Only a member of this blog may post a comment.