Consider the multiplication of the following unsigned long long
integers:
unsigned long long a=4294967297;
unsigned long long b=4294967297;
cout<<a*b<<endl;
8589934593
I did not expect this answer. Instead I was expecting to get:
18446744065119617025
Note that, according to this source, the largest integer that can be represented by an unsigned long long
is 18446744073709551615
(or in hexadecimal 0xffffffffffffffff
). This is by 8589934590
larger than my expected 18446744065119617025
, so that I was assuming this number could still be represented.
What is going on and how to resolve this issue?
EDIT:
You guys are right, I was playing around with different numbers and confused the results of 4294967297
and 4294967295
squared. With 7
at the end it does overflow. Thanks for pointing this out.
I think you're doing your math wrong:
slowpy3.8> 4294967297 * 4294967297
18446744082299486209
slowpy3.8> hex(_)
'0x10000000200000001'
slowpy3.8> 0xffffffffffffffff > 0x10000000200000001
False
slowpy3.8> math.log2(18446744082299486209)
64.0000000006718
slowpy3.8>