What if I try to assign values ​​greater than pow (2,64) -1 for unsigned long long in C ++?

If I have two unsigned long long values ​​say pow (10,18) and pow (10,19), and I multiply them and save the output in another variable of type unsigned long long ... the value we get is obviously not answer, but does it have any logic? We get a type of unwanted type every time we try to do this with arbitrarily large numbers, but do the logics with input values ​​have outputs?

+4
source share
2 answers

Unsigned integral types in C ++ obey the rules of modular arithmetic, i.e. represent integers modulo 2 N where N is the number of bits of an integral type value (possibly less than its sizeoftimes CHAR_BIT); in particular, the type has values ​​[0, 2 N ).

Therefore, when you multiply two numbers, the result is the residue mathematical result divided by 2 N .

The number N is available programmatically through std::numeric_limits<T>::digits.

+10
source

Yes, there is logic.

As KerreK wrote, integers are "wrapped" in 2 N bits that make up the width of their data type.

To make it easier, consider the following:

#include <iostream>
#include <cmath>
using namespace std;

int main() {

    unsigned char tot;

    unsigned char ca = 200;
    unsigned char ca2 = 200;

    tot = ca * ca2;

    cout << (int)tot;

    return 0;
}

(: http://ideone.com/nWDYjO)

char 1 (. 255 ), 200 * 200 40000. unsigned char, ,

"", tot

(ca*ca2) % 256

256 - char (1 ), 2 8

(pow (10,18) * pow (10,19))% 2 number_of_bits_of_unsigned_long_long (architecture_dependent)

+1

All Articles