Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What if I try to assign values greater than pow(2,64)-1 to 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 store the output in another variable of type unsigned long long...the value which we get is obviously not the answer but does it have any logic? We get a junk type of value each time we try to this with arbitrarily large numbers, but do the outputs have any logic with the input values?

like image 969
AJ95 Avatar asked Dec 19 '22 19:12

AJ95


1 Answers

Unsigned integral types in C++ obey the rules of modular arithmetic, i.e. they represent the integers modulo 2N, where N is the number of value bits of the integral type (possibly less than its sizeof times CHAR_BIT); specifically, the type holds the values [0, 2N).

So when you multiply two numbers, the result is the remainder of the mathematical result divided by 2N.

The number N is obtainable programmatically via std::numeric_limits<T>::digits.

like image 169
Kerrek SB Avatar answered May 13 '23 06:05

Kerrek SB