Library contents

Kotlin BigInteger.gcd

The greatest common divisor is the longest whole-unit piece that divides both ribbon lengths evenly.

A simple example

BigInteger.gcd

  1. Start with 6 and 4
  2. Do this Find the largest shared divisor
  3. Result 2
Two divides both 6 and 4 without a remainder. No larger number does.
Lesson.kt
import java.math.BigInteger

fun main() {
    println(BigInteger.valueOf(6).gcd(BigInteger.valueOf(4)))
}
Output
2

Syntax

Kotlin syntax
24.toBigInteger().gcd(36.toBigInteger())
Run these examples in Kotlin

Save one example at a time as Lesson.kt. Use Kotlin 2.2 on JDK 21.

kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar

Pack two ribbon lengths into equal pieces

A craft shop has two lengths of ribbon and wants equal pieces without leftovers. Find the largest length that divides both rolls before cutting the first strip.

Result12
Lesson.kt

fun main() {
    println(24.toBigInteger().gcd(36.toBigInteger()))
}
Output
12

A 24-centimetre ribbon yields two pieces of length twelve. A 36-centimetre ribbon yields three.

Advertisements

Cut equal fabric squares

A textile student has a rectangular piece measuring 18 by 30 centimetres. She wants the largest square size that tiles it without offcuts.

Given18 · 30
Worked result6

Using 18 · 30 gives 6 for this measurement.

Make identical sample kits

A teacher has 42 red counters and 28 blue counters. He wants the largest number of identical kits that uses every counter.

Given42 · 28
Worked result14

Using 42 · 28 gives 14 for this measurement.

What to watch for

Use the same smallest whole unit for both measurements before computing a divisor.

Documentation for BigInteger.gcd