The birthday bound says collisions in an n-bit hash arrive after about 2^(n/2) tries. Here you find the exact number for a target chance.
What to build
For a hash with 2^bits values, find the fewest random inputs that make a collision at least as likely as a target.
Requirements
- The chance of a collision among k inputs is 1 − Π (1 − i/2^bits) for i = 0 … k − 1.
- Find the smallest k with chance ≥ target / 100 and print it.
- Add the logarithms ln(1 − i/N) instead of multiplying many factors, so precision is kept.
Input
One line per question: bits and target percentage.
Output
One number per line.
Constraints
1 ≤ bits ≤ 32. The target is between 1 and 99.
Example
Input:
16 50
Output:
302
Why it works
The chance of no collision drops a little with each input, slowly at first and then quickly; around √(2^bits) inputs it falls past one half, which is where the birthday bound comes from.
Examples
16 50
302
8 50
20
Hints
Hint 1
Math.log1p(-i / N) is ln(1 − i/N) computed accurately.
Hint 2
Stop as soon as 1 − exp(sum) reaches the target.
Solution
Show one correct solution (try it yourself first)
let line = prompt();
while (line !== null) {
const [bits, target] = line.trim().split(/\s+/).map(Number);
const N = 2 ** bits;
let logNone = 0;
let k = 0;
while (1 - Math.exp(logNone) < target / 100) {
logNone += Math.log1p(-k / N);
k++;
}
console.log(String(k));
line = prompt();
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step