leapc
Loading...
Searching...
No Matches
quo_mod.c
Go to the documentation of this file.
1/* SPDX-License-Identifier: MIT */
9
10#include "quo_mod.h"
11
12struct quo_mod quo_mod(int x, int y) {
13 /*
14 * Compute modulus using C's % operator. Note that C's % operator will yield
15 * negative results when the numerator is negative.
16 */
17 int quo = x / y;
18 int mod = x % y;
19
20 /* Adjust negative modulus to be positive. Ensures that:
21 *
22 * 0 <= mod < y when y > 0
23 * y < mod <= 0 when y < 0
24 *
25 * This matches Lua's modulo operator behaviour.
26 */
27 if (mod != 0 && (mod ^ y) < 0) {
28 mod += y;
29 quo--;
30 }
31
32 return (struct quo_mod){.quo = quo, .mod = mod};
33}
Quotient and modulus prototypes.
Quotient and remainder in integer space.
Definition quo_mod.h:22
int mod
Integer modulus.
Definition quo_mod.h:30
int quo
Integer quotient.
Definition quo_mod.h:26