English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive Collection of Kotlin Examples
In this article, you will learn how to check if a number is prime. This is done using for in Kotlin.-Loop completed.
fun main(args: Array<String>) { val num = 29 var flag = false for (i in 2..num / 2) { //Condition for non-prime numbers if (num % i == 0) { flag = true break } } if (!flag) println("$num is a prime number.") else println("$num is not a prime number.") }
When running the program, the output is:
29 is prime.
Like Java, in the above program, the for loop is used to determine if the given number num is a prime number.
In the for loop, we check if this number can be divided by a given range (2..num/2Any number divides num. If so, flag is set to true, and we exit the loop. This determines that num is not a prime number.
If num cannot be divided by any number, then flag is false, and num is a prime number.
The following is equivalent Java code:Java program to check for prime numbers
fun main(args: Array<String>) { val num = 33 var i = 2 var flag = false while (i <= num / 2) { //Condition for non-prime numbers if (num % i == 0) { flag = true break } ++i } if (!flag) println("$num is a prime number.") else println("$num is not a prime number.") }
When running the program, the output is:
33 Not a Prime Number
In the above program, replace the for loop with a while loop. The loop will continue to run until i<=num/2. In each iteration, check if num can be divided by i, and increment the value of i1.
Visit this page to learn howDisplay All Prime Numbers Between Two Time Intervals.