How to create variable to contain a number with millions of digits?

1

I saw a report on the discovery of a prime number that contains 22 million digits. How could a variable contain a number, for example, with 100 million digits.

    
asked by anonymous 15.03.2016 / 00:11

2 answers

4

To put a very large number in memory, simple: save the digits as a large string , or whatever is closest to the machine, the number in binary format as an array of byte .

What you are probably asking is how to put this number into memory so that it behaves as a "common" number. For these cases there are data structures (or classes) that store the number in memory in any representation (probably byte[] ), with public methods that allow manipulating this mass of data as if it were a "pure" number.

Take a look: link (Java) and link (C #).

Other languages will have similar classes or structures. In fact, if you search for BigInteger (or BigDecimal ), you will see that you have several different third-party implementations of that class type in the most varied languages. That is, it is possible to create this kind of "big number" in the hand, without depending on the language that is working. In the end it's just a data structure (or class), which happens to do the same thing as the native numbers.

    
15.03.2016 / 04:22
3

Although it is technically possible to put the number in a variable, this is hardly possible. Usually allocates it in memory and the variable just points to it. At least this would be necessary if you really need to save all the digits. It is not always (see Bacco's comment). You have ways to represent the number without saving all your digits.

There are several ways to store all digits too. An obvious good thing would be to do the same thing you do to save a text of 100 million characters (a String , except that in this case it would be just numeric digits.)

All techniques will typically have to use some array of bytes. The encoding of this array can vary according to each need. Even if the number has some specific encoding.

It is often necessary to think beyond memory. If the number is too large it may not fit in memory. Even with the possibility of virtual memory, it may be useful to think of a solution designed to work with this disk number and to have more control over how this is done.

Some languages have their own type that already does this. The type is often called BigInteger or something like that.

    
15.03.2016 / 00:26