Kotlin with Copilot: How many prime numbers are there from 0 to 200
Video: Kotlin with Copilot: How many prime numbers are there from 0 to 200 by Taught by Celeste AI - AI Coding Coach
Watch full page →Kotlin with Copilot: Counting Prime Numbers from 0 to 200
In this example, we write a Kotlin program to count how many prime numbers exist between 0 and 200. The code demonstrates a simple function to check primality and iterates through the range to tally the primes. This is a practical way to practice loops, conditionals, and functions in Kotlin.
Code
fun isPrime(n: Int): Boolean {
if (n < 2) return false
for (i in 2..Math.sqrt(n.toDouble()).toInt()) {
if (n % i == 0) return false
}
return true
}
fun main() {
var count = 0
for (num in 0..200) {
if (isPrime(num)) {
count++
}
}
println("Number of prime numbers between 0 and 200: $count")
}
Key Points
- The isPrime function efficiently checks if a number is prime by testing divisors up to its square root.
- Kotlin's range syntax (0..200) makes iterating over a sequence of numbers concise and readable.
- Using a mutable variable to count primes demonstrates basic state management in Kotlin loops.
- Printing the result with string templates provides clear output formatting.
- This approach can be extended to larger ranges or optimized with advanced algorithms like the Sieve of Eratosthenes.