Skip to content

Instantly share code, notes, and snippets.

@valin4tor
Last active February 7, 2021 19:05
Show Gist options
  • Save valin4tor/719ef0658b90a984c9ca6d1417a46f03 to your computer and use it in GitHub Desktop.
Save valin4tor/719ef0658b90a984c9ca6d1417a46f03 to your computer and use it in GitHub Desktop.
Birthday collision calculator
use num::{
bigint::{BigUint, ToBigUint},
traits::One,
ToPrimitive,
};
fn factorial(num: u32) -> BigUint {
let mut result = BigUint::one();
for i in 1..=num {
result *= i;
}
result
}
fn birthday_probability(num_days: u32, num_people: u32) -> f32 {
let numerator = factorial(num_days);
let denominator =
num_days.to_biguint().unwrap().pow(num_people) * factorial(num_days - num_people);
let probability = numerator * 1000.to_biguint().unwrap() / denominator;
1.0 - probability.to_f32().unwrap() / 1000.0
}
fn main() {
let num_days = 365;
let num_people = 23;
println!(
"Probability of at least two people sharing a birthday with {} people: {}",
num_people,
birthday_probability(num_days, num_people)
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment