Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

C++ large numbers multiplication

Status
Not open for further replies.

3L4CK5C0RP10N

Programmer
Dec 25, 2004
5
0
0
PT
Hi.

Does anyone know why in a multiplication with large numbers, c++ returns negative numbers?

[ C++ ]

long Var;

Var = 228886641;
Var = Var * Var;

I need to know why this code returns -1820311071.

Help will be apreciated... [thumbsup2]
 
Probably because you are overflowing what a long can hold
An unsigned long can hold up to 4,294,967,295 or 2^32-1

as you are using signed numbers, you will get half that

You might look at 64 bit numbers, they should be big enough to hold the results of 228886641^2


"If it could have gone wrong earlier and it didn't, it ultimately would have been beneficial for it to have." : Murphy's Ultimate Corollary
 
Yes. I know that with 64 bits number works, but i was trying to know the way he returned a negative number.

Ex.:

The value should be 52389094428262881.

But how that returned -1820311071 ?

Thanks for your help...
 
The left-most bit of 32-bit word is a sign bit. Integer overflow = left bits are truncated. That's all. In that case you may get positive or negative (or zero;) truncated 32-bit patterns...
 
> ...but i was trying to know the way he returned a
> negative number.

Go back and reread snuv's post. Particularly the line that exactly answers your question:

> Probably because you are overflowing what a long
> can hold


Then, Google "twos complement" for a description of the way signed integers are stored and the way multiplication is implemented.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top