Condition in for loop


#1

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?


#2

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.


#3

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
}

And yes, it’s the first runnable sample of code ever in this forum ))


#4

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:


#5

How did you add runnable code to your post?


#6

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


#7

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


#8

Thanks