Skip to content

Instantly share code, notes, and snippets.

@MihailJP
Created May 17, 2014 10:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MihailJP/59a63439c1ee6e06f8ab to your computer and use it in GitHub Desktop.
Save MihailJP/59a63439c1ee6e06f8ab to your computer and use it in GitHub Desktop.
C++ modulo whose resulting sign is same as DIVISOR, not dividend
#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;
}
@MihailJP
Copy link
Author

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

Dividend Divisor Division Tr. Quot Fl. Quot. Remainder Modulo
⁻5 ⁺4 ⁻1.25 ⁻1 ⁻2 ⁻1 ⁺3
⁻4 ⁺4 ⁻1.00 ⁻1 ⁻1 0 0
⁻3 ⁺4 ⁻0.75 0 ⁻1 ⁻3 ⁺1
⁻2 ⁺4 ⁻0.50 0 ⁻1 ⁻2 ⁺2
⁻1 ⁺4 ⁻0.25 0 ⁻1 ⁻1 ⁺3
0 ⁺4 0.00 0 0 0 0
⁺1 ⁺4 ⁺0.25 0 0 ⁺1 ⁺1
⁺2 ⁺4 ⁺0.50 0 0 ⁺2 ⁺2
⁺3 ⁺4 ⁺0.75 0 0 ⁺3 ⁺3
⁺4 ⁺4 ⁺1.00 ⁺1 ⁺1 0 0
⁺5 ⁺4 ⁺1.25 ⁺1 ⁺1 ⁺1 ⁺1

Negative divisor

Dividend Divisor Division Tr. Quot Fl. Quot. Remainder Modulo
⁻5 ⁻4 ⁺1.25 ⁺1 ⁺1 ⁻1 ⁻1
⁻4 ⁻4 ⁺1.00 ⁺1 ⁺1 0 0
⁻3 ⁻4 ⁺0.75 0 0 ⁻3 ⁻3
⁻2 ⁻4 ⁺0.50 0 0 ⁻2 ⁻2
⁻1 ⁻4 ⁺0.25 0 0 ⁻1 ⁻1
0 ⁻4 0.00 0 0 0 0
⁺1 ⁻4 ⁻0.25 0 ⁻1 ⁺1 ⁻3
⁺2 ⁻4 ⁻0.50 0 ⁻1 ⁺2 ⁻2
⁺3 ⁻4 ⁻0.75 0 ⁻1 ⁺3 ⁻1
⁺4 ⁻4 ⁻1.00 ⁻1 ⁻1 0 0
⁺5 ⁻4 ⁻1.25 ⁻1 ⁻2 ⁺1 ⁻3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment