https://kotlinlang.org logo
#announcements
Title
# announcements
g

gaetan

02/17/2017, 9:56 AM
Copy code
fun <T> timeAndResult(block: () -> T): Pair<T, Long> {
    val start = System.currentTimeMillis()
    val result  = block()
    return Pair(result, System.currentTimeMillis() - start)
}

fun main(args: Array<String>) {
    val ret = timeAndResult {  Math.PI - (4 + calculatePiFor(1, 100_000_000))}
    println("Pi calculated to ${ret.first} precision in ${ret.second} ms")

    val ret2 = timeAndResult {  Math.PI - (4 + calculatePiFor2(1, 100_000_000))}
    println("Pi calculated to ${ret2.first} precision in ${ret2.second} ms")
}

fun calculatePiFor(start:Int, nb:Int):Double {
    var acc = 0.0
    for (i in start..(start+nb))
        acc += 4.0 * (1-(i % 2) * 2) / (2 * i + 1)
    return acc
}

fun calculatePiFor2(start:Int, nb:Int) =
        (start..(start+nb)).fold(0.0) { acc, i -> acc + 4.0 * (1-(i % 2) * 2) / (2 * i + 1)}