views:

262

answers:

6

Hello all,

Im facing a scenario where in ill have to compute some huge math expressions. The expressions in themselves are simple, ie have just the conventional BODMAS fundamental but the numbers that occur as operands are very large, to the tune of 1000 digit numbers. I do know of the BigInteger class of the java.math module but am looking for a different way so that the computation can occur also in a speedy manner. Im a guy still finding his feet in Java, so any pointers or advice in gthis regard would be of great help.

Regards p1nG

+4  A: 

Since you say you are new to Java, I would have to suggest you use BigInteger and BigDecimal unless you want to write your own arbitrarily large number handlers. BigInteger and BigDecimal are fast enough for most uses of them. The only time I've had speed issues with them is when dealing with numbers on the order of a million digits.

That is unless you have a specific need for not using BigInteger.

Poindexter
@all: Thank you for all the replies. I did try BigInteger and the problem that i faced was that when i try computing a string like "7+3" and then storing the result in BigInteger, it throws a NumberFormat exception. Any pointers on how this can worked on?
ping
What you want is `BigInteger("7").add(BigInteger("3"))`
Chinmay Kanchi
+10  A: 

Try it with BigInteger, profile the results with some test calculations, and see if it will work for you, before you look for something more optimized.

Jason S
+1  A: 

First write the program correctly (using BigFoo) and then determine if optimization is appropriate.

Thorbjørn Ravn Andersen
+1  A: 

BigInteger/BigFloat will be the most optimized implementation of generalized math that you will possibly get.

If you want it faster, you MIGHT be able to write assembly to use bit-shifting patters for specialized math (well, like divide by 2 tends to be a simple right shift), but if you are doing more than a few different types of equations, that will be very impractical.

BigInteger is only slow in comparison to int, but it will probably be the best you are going to possibly get for operations on numbers of more than 64 bits or so without going to another language--and even then you probably won't get much of an improvement unless that other language is assembly...

Bill K
A: 

I am surprised that equations with 1000 digits have a practical application (except perhaps encryption) Could you could explain what you are doing and what your speed requirements are?

Peter Lawrey
A: 

For the speedy manner you have to use divide and conquer algorithm. as i am also looking for same sort of problem because i am new to java so cant help you. but one of your problem can be solved by divide and conquer. e.g u hav numbers bigger then 2^32 or 12674344346374374374734737237237 some thing like this. if u solved it tell me also. thanks