Library contents

Java Math.ceilDivExact

Divide signed integers and round toward positive infinity with overflow checks.

A simple example

Math.ceilDivExact

  1. Start with 7 divided by 3
  2. Do this Round the quotient up
  3. Result 3
Two groups of three cover six. A third group covers the remaining one.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(Math.ceilDivExact(7, 3));
    }
}
Output
3

Syntax

Java syntax
Math.ceilDivExact(guests, seats)
JDK 21 method signatures (2)
public static int ceilDivExact(int x, int y)
public static long ceilDivExact(long x, long y)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Book enough tables while checking division

A booking clerk knows how many guests will arrive and how many fit at one table. Test a party that leaves a partial table so the final guest still has a seat.

From the programint guests = 17
Result5
Main.java

class Main {
    public static void main(String[] args) throws Exception {
        int guests = 17;
        int seats = 4;
        System.out.println(Math.ceilDivExact(guests, seats));
    }
}
Output
5

Four tables seat only sixteen guests. The seventeenth guest needs a fifth table.

Advertisements

Pack badges for two classrooms

A teacher has 31 badges and uses trays that hold eight each. All badges must travel, including those in a partially filled tray.

Given31 badges · 8 per tray
Worked result4 trays

Three trays carry 24 badges. The remaining seven need the fourth tray.

Send a full print batch

A print shop has 48 cards and cartons that hold twelve each. The packer checks whether another carton is needed after the fourth.

Given48 cards · 12 per carton
Worked result4 cartons

An exact multiple leaves no partial carton.

What to watch for

Validate a positive capacity first. Zero capacity raises ArithmeticException.

Documentation for Math.ceilDivExact