Ответ 1
+----+----+-----------+---------+-----------+-----------+---------+-----------+ | x mod y | quotient 'q' | remainder 'r' | | x | y | truncated | floored | Euclidean | truncated | floored | Euclidean | +----+----+-----------+---------+-----------+-----------+---------+-----------+ | 5 | 3 | 1 | 1 | 1 | 2 | 2 | 2 | | -5 | 3 | -1 | -2 | -2 | -2 | 1 | 1 | | 5 | -3 | -1 | -2 | -1 | 2 | -1 | 2 | | -5 | -3 | 1 | 1 | 2 | -2 | -2 | 1 | +----+----+-----------+---------+-----------+-----------+---------+-----------+
Любое из них удовлетворяет хотя бы x = yq + r
.
Усеченное деление и по модулю
static int truncatedDiv(int x, int y) {
return x / y;
}
static int truncatedMod(int x, int y) {
return x % y;
}
Плавающее деление и по модулю
Вы можете использовать методы в java.lang.Math
с Java 8. См. floorDiv и floorMod.
static int floorDiv(int x, int y) {
return Math.floorDiv(x, y);
}
static int floorMod(int x, int y) {
return Math.floorMod(x, y);
}
Евклидово деление и по модулю
a) на основе усеченного деления
import static java.lang.Math.*;
static int euclideanDiv(int x, int y) {
int r = x / y;
// if the divident is negative and modulo not zero, round down for positive divisor, otherwise round up
if (x < 0 && r * y != x) {
r -= signum(y);
}
return r;
}
static int euclideanMod(int x, int y) {
int r = x - euclideanDiv(x, y) * y;
return r;
}
b), основанный на разделении пола
import static java.lang.Math.*;
static int euclideanDiv(int x, int y) {
int r = floorDiv(x, y);
// if the divisor is negative and modulo not zero, round up
if (y < 0 && r * y != x) {
r++;
}
return r;
}
static int euclideanMod(int x, int y) {
int r = x - euclideanDiv(x, y) * y;
return r;
}
c), основанный на абсолютном модуле
import static java.lang.Math.*;
static int euclideanMod(int x, int y) {
int r = abs(x) % abs(y);
// apply the sign of divident and make sure the remainder is positive number
r *= signum(x);
r = (r + abs(y)) % abs(y);
return r;
}