Created
May 17, 2014 10:31
-
-
Save MihailJP/59a63439c1ee6e06f8ab to your computer and use it in GitHub Desktop.
C++ modulo whose resulting sign is same as DIVISOR, not dividend
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdexcept> | |
template<typename T> T modulo(T dividend, T divisor) { | |
if (divisor == static_cast<T>(0)) // division by zero is not allowed | |
throw std::domain_error("division by zero"); | |
if (dividend < static_cast<T>(0)) // dividend is negative | |
return -((-dividend) % (-divisor)); | |
else // dividend is non-negative | |
return dividend % divisor; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
About this Gist
Operator
%
of C++11 returns remainder whose resulting sign is same as dividend.However, in some cases, modulo whose resulting sign is same as divisor is preferred.
This template function calculates modulo of given dividend and divisor.
N. B. This implementation is intended for integer types only.
Positive divisor
Negative divisor