Math ceilDiv And unsignedMultiplyHigh
Page counts without off-by-one: Math.ceilDiv rounds the quotient up and rejects zero divisors; unsignedMultiplyHigh returns the 128-bit product's top half.
Code
public class BoundaryMath {
public static void main(String[] args) {
long items = 127;
long pageSize = 25;
// 127 / 25 = 5.08:ceilDiv 直接给出 6 页
System.out.println("pages = " + Math.ceilDiv(items, pageSize));
// 截断除法丢掉尾页:5 页装不下 127 条
System.out.println("truncated quotient = " + items / pageSize);
System.out.println("ceilDiv(17, 5) = " + Math.ceilDiv(17, 5));
System.out.println("ceilDiv(-17, 5) = " + Math.ceilDiv(-17, 5));
try {
Math.ceilDiv(1, 0);
} catch (ArithmeticException e) {
System.out.println("divide by zero throws ArithmeticException");
}
// 128 位乘积的高 64 位:无符号解读 0xFFFFFFFFFFFFFFFF × 2 = 1
long u = Math.unsignedMultiplyHigh(0xFFFF_FFFF_FFFF_FFFFL, 2L);
// 有符号解读 -1 × 2 = -2,高 64 位符号扩展为 -1
long s = Math.multiplyHigh(0xFFFF_FFFF_FFFF_FFFFL, 2L);
System.out.println("unsigned high = " + u + ", signed high = " + s);
}
}How the snippet works
The snippet is organized around the class BoundaryMath and the function main.
What to watch for
- Imports, when present, point only at standard-library modules.
Applying it
Entry signature: public static void main(String[] args)
The output comes back labeled — pages =, truncated quotient =, ceilDiv(17, 5) = — when the file runs.
Statements that decide the outcome
long u = Math.unsignedMultiplyHigh(0xFFFF_FFFF_FFFF_FFFFL, 2L);
long s = Math.multiplyHigh(0xFFFF_FFFF_FFFF_FFFFL, 2L);
long pageSize = 25;
Interactive Tools for This Topic
Date Add/Subtract CalculatorAdd or subtract days, weeks, months, or years from a date, clamping month ends such as January 31 plus one month.GCD & LCM CalculatorFind the greatest common divisor and least common multiple of two or more integers, computed exactly with BigInt.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Vector Similarity CalculatorCompute Cosine Similarity, Dot Product, Euclidean L2, Manhattan L1, and Chebyshev distances between numeric vectors with dimension checks.
FAQ
- What does Math ceilDiv And unsignedMultiplyHigh print when run?
- Execute the whole file; each printed line is prefixed with a label like `pages =`, `truncated quotient =`, `ceilDiv(17, 5) =`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.