Back to Blog

Kotlin: The last prime number

Sandy LaneSandy Lane

Video: Kotlin: The last prime number by Taught by Celeste AI - AI Coding Coach

Watch full page →

Kotlin: The Last Prime Number

This example demonstrates how to find the last prime number in a given range using Kotlin. Specifically, it checks numbers from 0 to 10 and identifies the highest prime within that range by iterating backwards and testing primality.

Code

fun isPrime(n: Int): Boolean {
  if (n < 2) return false
  for (i in 2..Math.sqrt(n.toDouble()).toInt()) {
    if (n % i == 0) return false
  }
  return true
}

fun lastPrimeInRange(start: Int, end: Int): Int? {
  for (num in end downTo start) {
    if (isPrime(num)) return num
  }
  return null
}

fun main() {
  val start = 0
  val end = 10
  val lastPrime = lastPrimeInRange(start, end)
  println("The last prime number between $start and $end is $lastPrime")
}

Key Points

  • Prime checking is done by testing divisibility up to the square root of the number.
  • Iterating backwards helps find the last (largest) prime efficiently.
  • Returning null handles the case when no prime exists in the range.
  • Kotlin’s concise syntax makes such algorithms easy to implement and read.