2 Keys Keyboard

medium dp math

Problem

Start with 1 'A'. Two ops: copy-all and paste. Minimum ops to print exactly n 'A's.

Inputn = 9
Output6
Copy then paste twice (×3), then copy and paste twice again (×3) → 9.

def min_steps(n):
    out = 0; d = 2
    while n > 1:
        while n % d == 0: out += d; n //= d
        d += 1
    return out
function minSteps(n) {
  let out = 0;
  for (let d = 2; n > 1; d++) while (n % d === 0) { out += d; n = n / d; }
  return out;
}
int minSteps(int n) {
    int out = 0;
    for (int d = 2; n > 1; d++) while (n % d == 0) { out += d; n /= d; }
    return out;
}
int minSteps(int n) {
    int out = 0;
    for (int d = 2; n > 1; d++) while (n % d == 0) { out += d; n /= d; }
    return out;
}
Time: O(√n) Space: O(1)