0
     println(measureNanoTime {
        println(isPrime2(999999999)) // O(n) ==> time is 182800 
    }
    )

    println(measureNanoTime {
        println(isPrime3(999999999)) // O(n/2) using step 2 ==> time is 6528700
    }
    )


    println(measureNanoTime {
        println(isPrime4(999999999)) // O(n/2) using while loop ==> time is 11401
        
    }
    )



fun isPrime2(n: Int): Boolean {
    if (n == 2) return true
    if (n < 2 || n % 2 == 0) return false

    for (i in 3 until n) {
        if (n % i == 0) return false
    }
    return true

}

fun isPrime3(n: Int): Boolean {
    if (n == 2) return true
    if (n < 2 || n % 2 == 0) return false

    for (i in 3 until n step 2) {
        if (n % i == 0) return false
    }
    return true

}

fun isPrime4(n: Int): Boolean {
    if (n == 2) return true
    if (n < 2 || n % 2 == 0) return false


    var i = 3;
    while (i < n) {
        if (n % i == 0) return false
        i += 2
    }
    return true

}
3bdoelnaggar
  • 1,109
  • 8
  • 18
  • 1
    This is not the correct way of benchmarking. Actually, in each case, your loop runs just once because 999999999 is divisible by 3. However, since one runs after the other, there may be some delay because the system might be busy with clean-up and setting the stage to execute the new code. You should at least write each of these as a separate program. However, the best thing to do would be to use some benchmarking API. – Arvind Kumar Avinash Jan 01 '23 at 21:48
  • thanks for the comment actually it doesn't run just one because i check modules of two not three, ya every time it runs it gives me different result, can you please provide to me any benchmarking apis links – 3bdoelnaggar Jan 01 '23 at 22:02
  • 2
    If you [convert the Kotlin code to Java](https://stackoverflow.com/q/34957430/4161471) `isPrime2()` and `isPrime4()` only use primitives and for-loops, while `isPrime3()` creates a new instance of `IntProgression`, which would take more time. I agree with @ArvindKumarAvinash though - [you need to benchmark properly to investigate](https://stackoverflow.com/a/20655996/4161471). Take a look at https://github.com/Kotlin/kotlinx-benchmark – aSemy Jan 01 '23 at 22:02
  • The answers to [this question](https://stackoverflow.com/q/20811061/4161471) are worth reading. They go into more detail about JVM benchmarking, with examples of how to use jmh. – aSemy Jan 01 '23 at 22:17

0 Answers0