> How do I use BigInteger in java? Do i have to import anything?

How do I use BigInteger in java? Do i have to import anything?

Posted at: 2014-12-18 
There's a fair amount of code required to make an arbitrary precision integer class. I built mine in C++, where operator overloads make the final result easier to use. A Java implementation is simpler.

The first thing you need to do is decide on a representation and "rules of the road". You could build a library for this, much like C would require, but using a Java class to make a user-defined type (UDT) is much nicer to use, and about the same amount of effort.

I'd recommend making the objects immutable, so that each arithmetic operation produces and returns a brand-new object containing the result.

The first things I'd implement are constructors to build a big integer from an int, a long, or a String containing a decimal representation, and a toString() method produce a printable String representation.

When it comes to arithmetic, you will maintain an array of digits in some base that you choose. Your code will do "digit-by-digit" computation with carry or borrow as needed.

Powers of 2 are easy to add and subtract and multiply without needing division to separate digit products into result digit and carry digits; and tend to be faster at computation. Powers of 10 are easier to convert to and from decimal for input and display; and also easier to debug since the the intermediate results make sense in terms of the decimal inputs and result. Nothing is perfect for every application.

You also have to decide how you want to represent negative numbers. Almost all fixed-precision binary arithmetic uses two's complement. That's not quite so convenient, though, for variable-sized numbers, and I found it easier to keep a separate sign and magnitude. My sign field wasn't a boolean though. I used a short int that's -1 for negative, +1 for positive or 0 if the number is zero. That makes it very easy to test for 0 as a special case.

As for how to write the code, I learned most of what I needed to know from two sources: elementary school arithmetic (most of all) and Donald Knuth's "The Art of Computer Programming" (Volume 2: Seminumerical Algorithms). I'm sure you can find newer stuff on a web search for "arbitrary precision arithmetic".

You don't "have" to import anything. You can write java.math.BigInteger each time you need it. Otherwise, you can import java.math.BigInteger and just refer to BigInteger each time you need it.

yes

see this tutorial http://compsci.ca/v3/viewtopic.php?t=131...

for your update, there are a number of ways to do it... you can write a class for it. The data structure is up to you, you simply need to make sure it supports all the mathematical operations.