Last active
December 29, 2018 11:21
-
-
Save sorokod/6a7d7053ef9761e083f79f61590a0eea to your computer and use it in GitHub Desktop.
Approximate Pi from randomly generated integers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.common.math.IntMath | |
import java.lang.Math.sqrt | |
import kotlin.random.Random.Default.nextInt | |
import kotlin.system.measureTimeMillis | |
/** | |
* Approximate Pi from randomly generated integers given that Pr( coPrime(n,m) ) = 6 / ( pi^2 ). | |
* Guava's implementation of GCD is about twice as fast as the "naive" one. | |
*/ | |
fun Pair<Int, Int>.gcd(): Int = | |
when (second) { | |
0 -> first | |
else -> Pair(second, first % second).gcd() | |
} | |
fun Pair<Int, Int>.gcdG() = IntMath.gcd(first, second) | |
fun main(args: Array<String>) { | |
val sample = 10_000_000 | |
val duration = measureTimeMillis { | |
val copCount = generateSequence { nextInt(2, 10_000) }.take(sample) | |
.zipWithNext() | |
.map { it.gcdG() } | |
.filter { it == 1 }.count() | |
val prob = copCount / (sample - 1).toDouble() | |
println(sqrt(6 / prob)) // 3.1414253391426907 | |
} | |
println("In $duration msec.") // In 1046 msec | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment