How to code a modulo operator in C C Obj-C that handles negative numbers

0 votes

As a mathematician, one of my pet peeves of C-derived languages is :

(-1) % 8 // comes out as -1, and not 7

fmodf(-1,8) // fails similarly

What is the most effective solution?

Templates and operator overloading are both possible in C++, but both are unfamiliar to me. 

Thank you for providing examples.

Jul 27, 2022 in C++ by Nicholas
• 7,760 points
1,852 views

No answer to this question. Be the first to respond.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
0 votes
First and foremost, I'd like to point out that you cannot rely on the assumption that (-1) % 8 == -1.

The sole certainty is that (x / y) * y + (x % y) == x.

However, whether or not the remainder is negative is determined by the implementation.

The binary / operator returns the quotient, whereas the binary percent operator returns the remainder of dividing the first expression by the second.

The behaviour is unknown if the second operand of / or percent is 0; otherwise, (a/b)*b + a % b equals a.

If both operands are nonnegative, the remainder is also nonnegative; otherwise, the remainder's sign is implementation-defined.

Here is a variant that handles both negative operands so that the result of subtracting the remainder from the divisor may be  subtracted from the dividend to get the real division's floor.

mod(-1,8) yields 7, but mod(13, -8) yields -3.
answered Aug 1, 2022 by Damon
• 4,960 points

edited Mar 5, 2025

Related Questions In C++

0 votes
1 answer

How to use new[ ] and delete[ ] operator in C++

int main(){ char *str; ...READ MORE

answered Jun 20, 2022 in C++ by Damon
• 4,960 points
1,304 views
0 votes
0 answers

How to find if a given key exists in a C++ std::map

I'm trying to check if a given ...