Write a Kotlin Program to Display Prime Numbers Between Intervals Using Function

As a Kotlin programmer, it’s important to understand the concept of prime numbers and how to generate them using functions.

In this tutorial, we’ll write a Kotlin program to display prime numbers between intervals using a function.

First, let’s define what a prime number is. A prime number is a positive integer greater than 1 that has no positive integer divisors other than 1 and itself.

In other words, a number is prime if it can only be divided by 1 and itself.

Now, let’s write the program to display prime numbers between intervals using a function.

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

fun displayPrimeNumbers(start: Int, end: Int) {
    for (i in start..end) {
        if (isPrime(i)) {
            println(i)
        }
    }
}

fun main() {
    val start = 2
    val end = 50
    displayPrimeNumbers(start, end)
}

In the above program, we have defined two functions – isPrime() and displayPrimeNumbers().

The isPrime() function takes an integer as an argument and returns true if the number is prime, and false otherwise.

The function checks whether the given number is less than or equal to 1, and if it is, it returns false.

Then, it checks whether the number is divisible by any number between 2 and the number’s half. If it is, the function returns false; otherwise, it returns true.

The displayPrimeNumbers() function takes two integers – start and end – as arguments and prints all prime numbers between them.

It does this by calling the isPrime() function for each number between start and end and printing the number if the function returns true.

Finally, in the main() function, we have defined the start and end values for the interval of prime numbers we want to display.

We then call the displayPrimeNumbers() function with these values to display the prime numbers between the given interval.

In conclusion, this program demonstrates how to generate prime numbers using functions in Kotlin.

By defining a function to check whether a number is prime, we can easily display all prime numbers between two intervals using another function that calls the first function for each number in the interval.