Вопрос

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.

Это было полезно?

Решение

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 values
  • BigDecimal: for numbers with decimal values

Check 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 );
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top