Home > Article > Backend Development > How to Implement a Custom Modulo Function for Negative Numbers in C/C /Obj-C?
Modulo Operator That Handles Negative Numbers in C/C /Obj-C
The modulo operator (%) in C-based languages, when applied to negative numbers, does not always behave intuitively. In particular, the result may be negative, even for positive divisors. This behavior can be frustrating, especially for mathematicians.
Custom Modulo Function
To address this issue, a custom modulo function can be implemented that handles negative numbers correctly. The following function uses the implementation-defined behavior of the modulo operator to ensure that the result is always positive:
int mod(int a, int b) { if (b < 0) { return -mod(-a, -b); } int ret = a % b; if (ret < 0) { ret += b; } return ret; }
This function works by first checking if the divisor is negative. If it is, the function calls itself recursively with the negation of the dividend and divisor. This ensures that the result will be positive.
Next, the function calculates the remainder of the division using the modulo operator. If the remainder is negative, the function adds the divisor to the remainder to make it positive.
Finally, the function returns the result.
Usage
The mod() function can be used in place of the modulo operator to obtain the desired behavior for negative numbers. For example:
int result = mod(-1, 8); // result is 7 result = mod(13, -8); // result is -3
The above is the detailed content of How to Implement a Custom Modulo Function for Negative Numbers in C/C /Obj-C?. For more information, please follow other related articles on the PHP Chinese website!