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.

JavaData Integrity

Code

snippet
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

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) =`.