Instantly share code, notes, and snippets.

# MihailJP/modulo.hpp

Created May 17, 2014 10:31
Show Gist options
• 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 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 template T modulo(T dividend, T divisor) { if (divisor == static_cast(0)) // division by zero is not allowed throw std::domain_error("division by zero"); if (dividend < static_cast(0)) // dividend is negative return -((-dividend) % (-divisor)); else // dividend is non-negative return dividend % divisor; }

### MihailJP commented May 17, 2014

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