Kotlin – Print Prime Numbers Between Two Given Numbers

Kotlin – How to Prime Numbers Between Two Given Numbers

In Kotlin, a prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Printing prime numbers between two given numbers involves finding all prime numbers within a specified range.

Examples

Example 1: Print Prime Numbers Between Two Given Numbers

Let’s start with an example of printing prime numbers between two given numbers.

We’ll create a function that takes two integers as input and prints all prime numbers between them.


fun isPrime(number: Int): Boolean {
    if (number <= 1) {
        return false
    }
    for (i in 2..number / 2) {
        if (number % i == 0) {
            return false
        }
    }
    return true
}

fun printPrimesInRange(start: Int, end: Int) {
    println("Prime numbers between $start and $end are:")
    for (num in start..end) {
        if (isPrime(num)) {
            println(num)
        }
    }
}

fun main() {
    // Test the function with a range
    val startNum = 10
    val endNum = 50
    printPrimesInRange(startNum, endNum)
}

Output

Prime numbers between 10 and 50 are:
11
13
17
19
23
29
31
37
41
43
47

In the program,

isPrime() Function

  1. We define a function isPrime that takes an integer as input and returns true if the number is prime, false otherwise.
  2. Inside the function, we check if the number is less than or equal to 1 (which is not prime). If so, we return false.
  3. We then loop from 2 to half of the number and check if any of these numbers divide the input number evenly (i.e., remainder is 0). If so, we return false.
  4. If none of the conditions are met, we return true indicating that the number is prime.

printPrimesInRange() Function

  1. We define a function printPrimesInRange that takes two integers as input: the starting and ending numbers of the range.
  2. Inside this function, we iterate through the range from start to end and check if each number is prime using the isPrime function.
  3. If a number is prime, we print it.

Summary

In Kotlin, you can print prime numbers between two given numbers by creating a function to check for prime numbers and iterating through the specified range to print the prime numbers found.