A 6-digit code has a million values. Whether an attacker can guess one depends on how many tries the server allows in each 30-second window.
What to build
Work out an attacker's chance of guessing a 6-digit TOTP code over some hours, and the largest number of tries per window that keeps the chance under 1%.
Requirements
- Each line has k (tries allowed per 30-second window) and h (hours of attack). There are 120 windows per hour.
- In each window the attacker tries k different codes, so a window succeeds with chance k ÷ 10⁶, independently of other windows.
- Print
chance P%with P to 4 decimal places, where P = (1 − (1 − k/10⁶)^windows) × 100. - Then print
under 1%: at most K per window, the largest K ≥ 0 whose chance over the same hours is below 1%.
Input
One line per question: k and h.
Output
Two lines per question.
Constraints
0 ≤ k ≤ 1000000 and 1 ≤ h ≤ 10000.
Example
Input:
10 24
Output:
chance 2.8389%
under 1%: at most 3 per window
Why it works
Each window is a fresh code, so the chance of failing every window is a product of equal factors; the chance only grows with more tries, so the largest safe K can be found by searching upward until the chance reaches 1%.
Examples
10 24
chance 2.8389% under 1%: at most 3 per window
3 1
chance 0.0360% under 1%: at most 83 per window
Hints
Hint 1
(1 - k / 1e6) ** windows gives the chance of failing every window.
Hint 2
K = 0 always has chance 0, so the search starts there and stops before the first K that reaches 1%.
Solution
Show one correct solution (try it yourself first)
const chance = (k, windows) => 1 - (1 - k / 1e6) ** windows;
let line = prompt();
while (line !== null) {
const [k, h] = line.trim().split(/\s+/).map(Number);
const windows = h * 120;
console.log(`chance ${(chance(k, windows) * 100).toFixed(4)}%`);
let K = 0;
while (K < 1000000 && chance(K + 1, windows) < 0.01) K++;
console.log(`under 1%: at most ${K} per window`);
line = prompt();
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step