With enough people in a room, two probably share a birthday, and far sooner than most people guess. Hash collisions follow the same maths.
What to build
For each line of people and days, print the chance that at least two people share a day.
Requirements
- Assume every day is equally likely and people are independent.
- chance = 1 − (d/d) × ((d − 1)/d) × … × ((d − n + 1)/d).
- Print the chance as a percentage with 2 decimal places, followed by
%.
Input
One line per question: people n and days d.
Output
One percentage per line.
Constraints
1 ≤ n ≤ 1000, 1 ≤ d ≤ 1000000. If n > d the chance is 100.00%.
Example
Input:
23 365
10 365
Output:
50.73%
11.69%
Why it works
The chance that everyone differs is the product of the chances that each new person avoids all earlier ones, and the chance of a shared day is one minus that.
Examples
Example 1 · Input
23 365 10 365
Expected output
50.73% 11.69%
Example 2 · Input
70 365
Expected output
99.92%
Hints
Hint 1
Multiply in a loop; once a factor is 0 the product stays 0.
Solution
Show one correct solution (try it yourself first)
let line = prompt();
while (line !== null) {
const [n, d] = line.trim().split(/\s+/).map(Number);
let allDifferent = 1;
for (let k = 0; k < n; k++) allDifferent *= Math.max(0, d - k) / d;
console.log(`${((1 - allDifferent) * 100).toFixed(2)}%`);
line = prompt();
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step