✨findSolution()
// start from n = 1, then
// • n + 5
// • n * 3
function findSolution(target) {
// check if n === target (recursive function)
function checkNode(n = 1, expr = '1') {
// base cases
if (n === target) return expr; // target found
if (n > target) return null; // no solution
// recursive cases (two branches)
return (
checkNode(n + 5, `(${expr} + 5)`) ||
checkNode(n * 3, `(${expr} * 3)`)
)
}
// check from n = 1
return checkNode();
}Last updated