#JavaScript (ES6), 98 bytes Inspired by [notjagan's Python answer][1]. Turns the input expression into a huge and ugly executable string. <!-- language: lang-js --> s=>eval(s.split`)(`.join`)*(`.split`(`.join`(g=(n,k)=>(C=d=>n%--d?C(d):k-=d<2)(++n)?g(n,k):n)(1,`) Merging the `C` and `g` functions into a single one may save some bytes, but it would require even more recursion. ###Test cases <!-- begin snippet: js hide: true console: true babel: false --> <!-- language: lang-js --> let f = s=>eval(s.split`)(`.join`)*(`.split`(`.join`(g=(n,k)=>(C=d=>n%--d?C(d):k-=d<2)(++n)?g(n,k):n)(1,`) ;[ "()", // 2 "(())", // 3 "()()", // 4 "((()))", // 5 "()(())", // 6 "(()())", // 7 "()()()", // 8 "(())(())", // 9 "()((()))", // 10 "()()((()))((()))", // 100 "(()(()(())))", // 101 "(()())(((())))(()(()))", // 1001 "(((((((())))))))", // 5381 "(()())((((()))))(()()(())(()))", // 32767 "()()()()()()()()()()()()()()()" // 32768 ] .forEach(s => console.log(s, '-->', f(s))) <!-- end snippet --> [1]: https://codegolf.stackexchange.com/a/150499/58563