Library contents

Groovy Math.divideExact

Divide integers with truncation toward zero and detect signed overflow.

A simple example

Math.divideExact

  1. Start with 7 and 3
  2. Do this Divide as integers
  3. Result 2
Three fits into seven twice. Integer division discards the remaining fraction here.
Lesson.groovy
println(Math.divideExact(7, 3))
Output
2

Syntax

Groovy syntax
Math.divideExact(credits, players)
Run these examples in Groovy

Save one example at a time as Lesson.groovy. Use Groovy 4 on JDK 21.

groovy Lesson.groovy

Divide reward credits into whole shares

A rewards desk splits credits into whole shares. Work with signed totals carefully because division near zero can produce a different result under different integer rounding rules.

From the programint credits = 17
Result4
Lesson.groovy
int credits = 17
int players = 4
println(Math.divideExact(credits, players))
Output
4

Each of four players receives four whole credits. The remainder can be assigned separately.

Advertisements

Make complete paint sets

A studio has 29 paint tubes and puts six in each set. It lists only sets that can be handed out complete.

Given29 tubes · 6 per set
Worked result4 sets

Four sets use 24 tubes. Five tubes stay on the shelf.

Share a complete batch of tickets

Forty tickets are shared equally among eight activity groups. The organizer records the whole-number share per group.

Given40 tickets · 8 groups
Worked result5 tickets

Every ticket is allocated because the division has zero remainder.

What to watch for

Despite its name, this method allows a remainder. Zero divisors and the minimum value divided by minus one raise an exception.

Documentation for Math.divideExact