Last active
March 17, 2017 13:28
-
-
Save romuloceccon/1292c9eae1edb515a620e7416559bc82 to your computer and use it in GitHub Desktop.
How to calculate modulo division (like Python's divmod) in C without conditionals (also works in Java)
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 <stdio.h> | |
| int main() | |
| { | |
| int i; | |
| static const int dm = 4; | |
| for (i = -2 * dm; i < 2 * dm; i++) { | |
| int rem = i % dm; | |
| int mod = (rem + dm) % dm; | |
| int div = (i - mod + rem) / dm; | |
| printf("%3d %3d %3d\n", i, div, mod); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment