Is there any data type available in Java or C++ which can hold integer values of 20 digits or more? The long long data type can hold only till 18 digits.
BigInteger: The BigInteger class allocates as much memory as it needs to hold all the bits of data it is asked to hold and also provides operations analogues to all of Java's primitive integer operators and for all relevant methods from java.
The INTEGER data type stores whole numbers that range from -2,147,483,647 to 2,147,483,647 for 9 or 10 digits of precision. The number 2,147,483,648 is a reserved value and cannot be used. The INTEGER value is stored as a signed binary integer and is typically used to store counts, quantities, and so on.
Long can store 10 digit easily. Long phoneNumber = 1234567890; It can store more than that also. This means it can store values of range 9,223,372,036,854,775,807 to -9,223,372,036,854,775,808.
Java specific:
You are looking for BigInteger
Immutable arbitrary-precision integers. All operations behave as if BigIntegers were represented in two's-complement notation (like Java's primitive integer types)
For ex:
BigInteger bint = new BigInteger("1234567856656569");
BigInteger bint2 = new BigInteger("1234556567856656569");
System.out.println(bint2.intValue()-bint.intValue()); //397189120
And BigDecimal
Take a look at java BigInteger.
In java
you can use:
BigInteger
: for numbers without decimal valuesBigDecimal
: for numbers with decimal valuesCheck out The Large Integer Case Study in C++.pdf by Owen Astrachan. I found this file extremely useful with detail introduction and code implementation. It doesn't use any 3rd-party library. I have used this to handle huge numbers (as long as you have enough memory to store vector<char>
) with no problems.
I have answered a similar question here, where I gave a more detailed introduce.
For C++, you can check out Matt McCutchen's Big Integer class, for Java just use BigInteger
BigInteger
class in Java can hold such numbers.
Alternatively, you can implement your own class, based on two long long numbers.
For C++, see Boost's excellent multiprecision library.
Use BigInt datatype with its implicit operations
Here is an example of addition
BigInteger big1 = new BigInteger("1234567856656567242177779");
BigInteger big2 = new BigInteger("12345565678566567131275737372777569");
BigInteger bigSum = big1.add(big2);
System.out.println(bigSum );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With