Jonas Jonas - 3 months ago 22
C++ Question

unsigned long long arithmetics

I'd like to multiply two

unsigned integers
but I want the result to be in an
unsigned long long
variable

unsigned long long M;
unsigned int X;
unsigned int Y;

X = 999999;
Y = 9990;
M = X * Y;


M
should be
9989990010
but for some reason it keeps being
1400055418


I've been troubled with this for a week now, and I think I reached the point where I want to cry!

Answer

You need to cast the X and Y to long long.

M = (unsigned long long)X * Y;

Enough to cast one of them the result will be based on the larger type.

Otherwise the result will be int, hence the overflow. It will be casted to long long on assignment, but that would be too late:-)