Condition in for loop

Let’s say I want to write:

for (int i = 2; i*i <= n; ++i) {}

Is there a way to write this in Kotlin without while?

There is a way but it’s not very pleasant:

for (i in 2..Math.sqrt(n.toDouble()).toInt()) {}

Frankly, I’d just use while for cases such as this.

1 Like

You can do something like this. But I don’t think it’s worth it :wink:

fun main(args: Array<String>){
      //sampleStart
    val n = 10
    for (i in generateSequence(1) { it + 1 }.takeWhile{ it * it < n })
        println(i)  
      //sampleEnd
}
10 Likes

Since the only requirement was to do it without while:

fun main(args: Array<String>) {
    val n = 10
    tailrec fun loop(i: Int): Unit = if (i * i < n ) Unit else loop(i + 1)
    loop(2)
}

:wink:

How did you add runnable code to your post?

You may use run-kotlin as a language name in ``` markdown syntax

3 Likes

This is incorrect, the condition is p*p <= n not p <= sqrt(n). But thanks anyway.

Thanks