# findSolution()

[JS](../../../..) ⟩ [value](../../..) ⟩ [function](../..) ⟩ [recursive]() ⟩ findSolution()

{% hint style="success" %}
by <mark style="color:yellow;">**starting from 1**</mark> and <mark style="color:red;">**repeatedly**</mark> either <mark style="color:blue;">**+ 5**</mark> or <mark style="color:blue;">**\* 3**</mark>, an infinite set of numbers can be produced. <mark style="color:yellow;">**given a number**</mark>, tries to <mark style="color:yellow;">**find a solution**</mark> of such additions and multiplications that produces that number.
{% endhint %}

{% tabs %}
{% tab title="💾 程式" %}
* replit ⟩ [findSolution(x)](https://replit.com/@pegasusroe/findSolutionx#index.js)

```javascript
// 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();
}
```

💈範例：&#x20;

```javascript
findSolution(26),    // (((((1 + 5) + 5) + 5) + 5) + 5)
findSolution(23),    // (((1 + 5) * 3) + 5)
findSolution(82),    // ((((((1 * 3) + 5) * 3) * 3) + 5) + 5)
```
{% endtab %}

{% tab title="📗 參考" %}
* [ ] Eloquent JavaScript ⟩ [Recursion](https://eloquentjavascript.net/03_functions.html#h_jxl1p970Fy)
{% endtab %}

{% tab title="📘 手冊" %}
* [ ] [Recursion](https://developer.mozilla.org/en-US/docs/Glossary/Recursion)
{% endtab %}
{% endtabs %}
