Kotlin Program to Check Prime Number with Output
for (i in 2..sqrt(n.toDouble()).toInt()) and returns false if any divisor is found, otherwise true.Examples
How to Think About It
Algorithm
Code
import kotlin.math.sqrt fun isPrime(n: Int): Boolean { if (n < 2) return false for (i in 2..sqrt(n.toDouble()).toInt()) { if (n % i == 0) return false } return true } fun main() { val number = 17 if (isPrime(number)) { println("$number is a prime number") } else { println("$number is not a prime number") } }
Dry Run
Let's trace the number 17 through the code to see how it checks for primality.
Check if number is less than 2
17 is not less than 2, so continue.
Calculate square root
Square root of 17 is approximately 4.12, so check divisors from 2 to 4.
Check divisibility by 2
17 % 2 = 1 (not zero), continue.
Check divisibility by 3
17 % 3 = 2 (not zero), continue.
Check divisibility by 4
17 % 4 = 1 (not zero), no divisors found.
Return result
No divisors found, so 17 is prime.
| Divisor | 17 % Divisor | Divides Evenly? |
|---|---|---|
| 2 | 1 | No |
| 3 | 2 | No |
| 4 | 1 | No |
Why This Works
Step 1: Check for numbers less than 2
Numbers less than 2 are not prime by definition, so we return false immediately.
Step 2: Limit divisor checks to square root
Checking divisors only up to the square root reduces work because any factor larger than the square root pairs with a smaller factor already checked.
Step 3: Return true if no divisors found
If no number divides evenly, the number is prime, so we return true.
Alternative Approaches
fun isPrime(n: Int): Boolean {
if (n < 2) return false
for (i in 2 until n) {
if (n % i == 0) return false
}
return true
}fun isPrime(n: Int, i: Int = 2): Boolean { if (n < 2) return false if (i > kotlin.math.sqrt(n.toDouble()).toInt()) return true if (n % i == 0) return false return isPrime(n, i + 1) }
Complexity: O(√n) time, O(1) space
Time Complexity
The loop runs up to the square root of n, so the time grows roughly with √n.
Space Complexity
Only a few variables are used, so space is constant O(1).
Which Approach is Fastest?
Checking up to the square root is fastest among simple methods; checking up to n-1 is slower, and recursion adds overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Check up to √n | O(√n) | O(1) | Efficient and simple |
| Check up to n-1 | O(n) | O(1) | Simple but slower |
| Recursive check | O(√n) | O(√n) due to call stack | Elegant but less efficient |