^ ( # Find the largest prime factor of N, and capture it in \2 (?= # Repeatedly divide tail by its smallest prime factor until what's left is prime, # which will then be captured in \2. ( (xx+)(?=\3+$) # tail /= {smallest prime factor of tail} | x* # Capture the remaining prime )+ ) # Divide: \4 = N / \2, with \5 = \4-1, enforcing that \5 > 0 # We can skip the capture of and test for divisibility by \2-1 because \2 is prime. (?= ( # \4 = N / \2 (x+) # \5 = \4-1 (?=\2\5*$) x ) \4*$ ) # Find the next smaller prime than \2 and capture it in \7, with \8 = \7-1 (?= .*(?=\2$).+? (?!(xx+)\6+$) (x(x*\5)) # Simultaneously capture \7 and enforce that \5 < \7 ) # Multiply: tail = \7 * \5 .* (?=\7+$) (?=\5\8+$) )* xx$