JS ⟩ value ⟩ function ⟩ recursive ⟩ findSolution()
by starting from 1 and repeatedly either + 5 or * 3 , an infinite set of numbers can be produced. given a number , tries to find a solution of such additions and multiplications that produces that number.
💾 程式 📗 參考 📘 手冊
Copy // 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 ();
}
💈範例:
Copy findSolution ( 26 ) , // (((((1 + 5) + 5) + 5) + 5) + 5)
findSolution ( 23 ) , // (((1 + 5) * 3) + 5)
findSolution ( 82 ) , // ((((((1 * 3) + 5) * 3) * 3) + 5) + 5)