Retina, 2929 26 bytes
.+\d+
$*
(?=1+¶=.*?(1+)$)\1|1+$\1
$'
1
Try it online!Try it online! Link includes test cases and header to reformat them to its preferred input (0-indexed k
on first line, 1-indexed n
on second line). I was inspired by @GB's Ruby answer. Explanation:
.+\d+
$*
Convert to unary.
(?=1+\n=.*?(1+)$)\1|1+$\1
$'
Match every string of n
within k
, and replace the match with everything after the match. This is k-n
, k-2n
, k-3n
, but n
is also after the match, so you get k
, k-n
, k-2n
etc. All that remains is to deleteThis also matches n
, which is handled by the alternationsimply deleted (it's no longer needed).
1
Sum the results and convert back to decimal.