java – How to work with values ​​that far exceed the long (64-bit) threshold value

Question:

How are operations stored and performed on numbers that exceed limit values ​​of type long and double ? How are the four primary operations done with these numbers (addition, subtraction, multiplication and division)?

Context

It is common for most programming languages ​​to support long and double types (both use a 64-bit word) however in Supercomputers (such as those that do atomic bomb calculations and meteorological and astronomical data processing) that have thousands of cores of processing and TBs of RAM working concurrently should probably work with values ​​that far exceed the supported long and double values.

Example of values ​​that far exceed the supported long and double values.

  • googol
  • googolplex
  • mol (chemical unit)
  • Long.MAX_VALUE * Long.MAX_VALUE * Long.MAX_VALUE ( JAVA )
  • googolplex * googolplex

What would be possible solutions in C (high performance) and Java (very popular)

Answer:

How large numbers are represented and stored will depend on your programming language. In languages ​​like C and Java , the most they offer you are libraries that implement giant numbers. But in languages ​​like Python3 and Haskell , you don't have to worry about popping a variable because the number is too big. Examples of use:


In C , using the gmp library :

# include <stdio.h>
# include <gmp.h>

int main(int argc, char *argv[]) {
    mpz_t a, b;
    mpz_init_set_str (a, "987654321987654321000000000", 10);
    mpz_init_set_str (b, "987654321987654321000000000", 10);
    mpz_mul (a, a, b); // a = a * b

    printf("%s\n", mpz_get_str (NULL, 10, a));
    return 0;
}

Result: 975461059740893157555403139789971041000000000000000000 .

Note: The .c file must be compiled with the following command to include the gmp library: gcc ARQUIVO.c -lgmp -lm .


In Java , using the BigInteger class:

import java.math.BigInteger;

public class Main {
    public static void main(String[] args) {
        BigInteger b1 = new BigInteger("987654321987654321000000000");
        BigInteger b2 = new BigInteger("987654321987654321000000000");

        BigInteger produto = b1.multiply(b2);

        System.out.println(produto);
    }
}

Result: 975461059740893157555403139789971041000000000000000000 .


In Haskell , with native support:

Prelude> 987654321987654321000000000 * 987654321987654321000000000
975461059740893157555403139789971041000000000000000000

In Python3 , also with native support:

>>> 987654321987654321000000000 * 987654321987654321000000000
975461059740893157555403139789971041000000000000000000
Scroll to Top