Sivateja.koppineedi
Sivateja.koppineedi

Reputation: 178

What datatype to use for 40 digit integers in java

For example

first number = 123456.....40 digits
second number = 123456.....40digits

Then I need to store the number

third = first * second;

after that I need to print third and again I need to perform operation like

fourth = third * third;

and print fourth. So how can I handle that much long integers which data type I need to use?

Upvotes: 1

Views: 1886

Answers (2)

user1097772
user1097772

Reputation: 3549

See this question its similar Arbitrary-precision arithmetic Explanation the answer explain it quite good.

The basic is that you work with smaller parts. Just remember how you learned to work with big numbers in school (2-3 grade) you wrote down two numbers and

 2351
  *12
 -----
 4702
2351
------
28212

You just do small operations and store them somewhere you can put them in string or better in some array of integers. Where for example

number 123456789123456789 can be number[0] = 6789 number[1] = 2345 number[3] = 7891 number[4] = 2345 number[5] = 1 String numberToShow = ""; for(int i = 0; i

There are some links for computer arighmetics https://en.wikipedia.org/wiki/Category:Computer_arithmetic and for adders https://en.wikipedia.org/wiki/Category:Adders_(electronics)

In your computer you have basically also just some adders which can work only with some size of numbers and if you need to work with bigger you need to split it in smaller parts.
Some of this parts can be done parallel, so you can speed up your algorithm. These are usually more sophisticated.
But the basic principe is similar to working with big numbers on your primary school.

Upvotes: 0

Papershine
Papershine

Reputation: 5223

Use BigInteger class in java.math, then use BigInteger.multiply to multiply them together.

Check here for more on how to use it: https://www.tutorialspoint.com/java/math/biginteger_multiply.htm

Upvotes: 2

Related Questions