Copilot: Get the first 10 prime numbers
Video: Copilot: Get the first 10 prime numbers by Taught by Celeste AI - AI Coding Coach
Watch full page →Copilot: Get the first 10 prime numbers in Kotlin
Generating prime numbers is a common programming exercise that helps understand loops and conditionals. Here, we use Kotlin to find and print the first 10 prime numbers by checking each candidate number for divisibility.
Code
fun main() {
val primes = mutableListOf<Int>() // List to store prime numbers
var number = 2 // Start checking from 2, the first prime number
while (primes.size < 10) {
if (isPrime(number)) {
primes.add(number) // Add number if it is prime
}
number++
}
println("First 10 prime numbers: $primes")
}
// Function to check if a number is prime
fun isPrime(num: Int): Boolean {
if (num < 2) return false
for (i in 2..Math.sqrt(num.toDouble()).toInt()) {
if (num % i == 0) return false
}
return true
}
Key Points
- Start checking for primes from 2, since 1 is not a prime number.
- Use a helper function to test divisibility up to the square root of the candidate number.
- Collect prime numbers in a list until you reach the desired count (10 in this case).
- Kotlin’s concise syntax makes it easy to write clear and readable prime-checking logic.