Skip to content

Instantly share code, notes, and snippets.

@sorokod
Last active December 29, 2018 11:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sorokod/6a7d7053ef9761e083f79f61590a0eea to your computer and use it in GitHub Desktop.
Save sorokod/6a7d7053ef9761e083f79f61590a0eea to your computer and use it in GitHub Desktop.
Approximate Pi from randomly generated integers
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