Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Modulo
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Common pitfalls== When the result of a modulo operation has the sign of the dividend (truncated definition), it can lead to surprising mistakes. For example, to test if an integer is [[parity (mathematics)|odd]], one might be inclined to test if the remainder by 2 is equal to 1: <syntaxhighlight lang="cpp"> bool is_odd(int n) { return n % 2 == 1; } </syntaxhighlight> But in a language where modulo has the sign of the dividend, that is incorrect, because when {{math|''n''}} (the dividend) is negative and odd, {{math|''n''}} mod 2 returns β1, and the function returns false. One correct alternative is to test that the remainder is not 0 (because remainder 0 is the same regardless of the signs): <syntaxhighlight lang="cpp"> bool is_odd(int n) { return n % 2 != 0; } </syntaxhighlight> Or with the binary arithmetic: <syntaxhighlight lang="cpp"> bool is_odd(int n) { return n & 1; } </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)