unexpected result of % function

Hi, I am very new to C++ and I don't understand why

(16807*1622647863)%2147483647 evaluates to a negative number (-1199696159)

it should be positive. Thank you for your help
Last edited on
You're going a bit out of bounds of the integral type here, no? The bound on integers is 4,294,967,296, and the left-hand side exceeds that.

-Albatross
Oh yes, I forgot about this. What can I use instead?
EDIT: unsigned long.

-Albatross
Last edited on
that doesn't work either. same result
The typical upper bound for long is also 2,147,483,647.
You'd need to use long long to calculate that, but why bother? The exact value of that expression is 947800188, which fits nicely into a 32-bit integer.
The problem is that its not evaluated to be 947800188. Without declaring any variables the command

cout<<(16807*1622647863)%2147483647<<endl;

gives the negative value. Why?
Oh, sorry. I thought you were just trying to get it to work.
The problem is that the default type for integer literals is int. In your implementation, int seems to be a 32-bit signed integer. 16807*1622647863 gives 18CD B87E 16E1, but that doesn't fit in 32 bits, so it's truncated to B87E 16E1 (-1199696159). The value is negative due to two's complement (http://en.wikipedia.org/wiki/Two's_complement ).
The type of a literal can be changed be adding suffixes: 16807ULL * 1622647863ULL. "ULL" means "this literal is an unsigned long long".
Note that long long is not standard, but it's supported in most implementations.
Thank you, now it works!
If you want to play with modular arithmetic, you might want to check out the Mongomery reduction.
http://www.nugae.com/encryption/fap4/montgomery.htm

This is cool stuff! (But unnecessary, I think, to your current needs.)
Topic archived. No new replies allowed.