I am currently wirinting a method involving BigInteger. Method accepts BigInteger and increases its value by 1 in a loop till some criteria is met. For adding one to Big Integer, I am using BigInteger.add() method. Big Integer is immutable object as per API.So add() method returns new Big Integer.
Problem is if number is too big and criteria is not met for a while, program hangs. For e.g. numbers above 1000000 ,program hangs.Any idea how to avoid this?
Surely you meant BigInteger.valueOf(...) in those examples instead of String.valueOf(...)?
Note that class BigInteger has a few constants, which would make it slightly more efficient:
But why are you using BigInteger for this, could the search in the while loop really take more iterations than would fit in a long (2^63 - 1 = 9,223,372,036,854,775,807 iterations?!) or even in an int (2^31 - 1 = 2,147,483,647 iterations)? Use a long or int instead of a BigDecimal.
Your program does not appear to hang at all. It appears to take a very long time to complete its loop. Assuming 10 nanoseconds for one iteration of the loop, then going from 9.99999999999999999999 × 10^99 to 10^100 requires 10^80 iterations which will take 10^72 seconds which is approx 3.17 × 10^64 years.
This is a good example of why searching algorithms are non-trivial. Also a good example where a binary search, O(log(n)), makes a big difference to a polynomial search, O(n). Granted, I have no idea if a binary search (or any other intelligent searching algorithm) can be applied here but unless you have near infinite time, I'd suggest finding one.