20#define luai_nummod(a, b) ((a) - floor((double)(a) / (b)) * (b))
22static double nummod(
double x,
double y) {
return luai_nummod(x, y); }
24static void check_quo_mod(
int x,
int y) {
25 const long long trunc_quo = (
long long)x / y;
26 const long long trunc_mod = (
long long)x % y;
27 long long expected_quo = trunc_quo;
28 long long expected_mod = trunc_mod;
30 if (expected_mod != 0 && (expected_mod < 0) != (y < 0)) {
36 assert(qm.
quo == expected_quo);
37 assert(qm.
mod == expected_mod);
38 assert((
long long)x == (
long long)y * qm.
quo + qm.
mod);
40 assert(0 <= qm.
mod && qm.
mod < y);
42 assert(y < qm.
mod && qm.
mod <= 0);
45int quo_mod_test(
int argc,
char **argv) {
46 static const int boundary_values[] = {
47 INT_MIN, INT_MIN + 1, -2, -1, 0, 1, 2, INT_MAX - 1, INT_MAX,
58 {INT_MIN, 3, INT_MIN / 3 - (INT_MIN % 3 != 0), INT_MIN % 3 + (INT_MIN % 3 != 0 ? 3 : 0)},
59 {INT_MIN, -3, INT_MIN / -3, INT_MIN % -3},
60 {INT_MAX, -3, INT_MAX / -3 - (INT_MAX % -3 != 0), INT_MAX % -3 - (INT_MAX % -3 != 0 ? 3 : 0)},
61 {INT_MAX, INT_MIN, -1, -1},
62 {INT_MIN, INT_MIN, 1, 0},
63 {INT_MIN, INT_MAX, INT_MIN / INT_MAX - (INT_MIN % INT_MAX != 0),
64 INT_MIN % INT_MAX + (INT_MIN % INT_MAX != 0 ? INT_MAX : 0)},
67 for (
size_t i = 0; i <
sizeof cases /
sizeof cases[0]; i++) {
68 const int x = cases[i].x;
69 const int y = cases[i].y;
71 assert(qm.
quo == cases[i].quo);
72 assert(qm.
mod == cases[i].mod);
73 assert((
long long)x == (
long long)y * qm.
quo + qm.
mod);
75 assert(0 <= qm.
mod && qm.
mod < y);
77 assert(y < qm.
mod && qm.
mod <= 0);
85 for (
size_t i = 0; i <
sizeof boundary_values /
sizeof boundary_values[0]; i++)
86 for (
size_t j = 0; j <
sizeof boundary_values /
sizeof boundary_values[0]; j++) {
87 const int x = boundary_values[i];
88 const int y = boundary_values[j];
89 if (y == 0 || (x == INT_MIN && y == -1))
99 for (
int x = -333; x <= 333; x++)
100 for (
int y = -333; y <= 333; y++) {
Quotient and modulus prototypes.
struct quo_mod quo_mod(int x, int y)
Compute the integer quotient and modulus.
Quotient and remainder in integer space.