Prime Number Program in Kotlin
In Kotlin, you can check if given number n
is a Prime number or not, by checking if there is any factor in the range of [2, n/2]
.
To iterate over possible factors, you can use a For loop statement.
Program
In the following program, we write a function isPrime()
that takes an integer value, and checks if the given integer value is a Prime number or not. If the given value is a Prime number, then the function returns true
, or else, it returns false
.
Kotlin Program
fun isPrime(n: Int): Boolean {
var i = 2
while (i < n / i) {
if (n % i == 0) {
return false
}
i++
}
return true
}
fun main() {
val n = 19
if (isPrime(n)) {
println("$n is a Prime Number.")
} else {
println("$n is not a Prime Number.")
}
}
Output
19 is a Prime Number.