Skip to content

Instantly share code, notes, and snippets.

@oliverbenns
Last active November 1, 2019 05:08
Show Gist options
  • Save oliverbenns/b99b78bf9b97d6a9c89e463270aa181a to your computer and use it in GitHub Desktop.
Save oliverbenns/b99b78bf9b97d6a9c89e463270aa181a to your computer and use it in GitHub Desktop.
Birthday Problem in Go
package main
import "fmt"
import "math"
import "math/big"
func bigFactorial(n int64) *big.Int {
if (n > 0) {
x := bigFactorial(n - 1)
m := big.NewInt(n)
return x.Mul(m, x)
}
return big.NewInt(1)
}
func birthdayProbability(num int64) float64 {
allPermutations := bigFactorial(365)
offsetPermutations := bigFactorial(365 - num)
totalPermutations := new(big.Int).Div(allPermutations, offsetPermutations)
totalBirthdays := big.NewFloat(math.Pow(365, float64(num)))
notSameProbability, _ := new(big.Float).Quo(new(big.Float).SetInt(totalPermutations), totalBirthdays).Float64()
return 1 - notSameProbability
}
func main() {
result := birthdayProbability(70)
fmt.Printf("Probability is %f\n", result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment