Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

008-loop: 末尾再帰になっていない? #124

Open
cympfh opened this issue Sep 20, 2019 · 0 comments
Open

008-loop: 末尾再帰になっていない? #124

cympfh opened this issue Sep 20, 2019 · 0 comments

Comments

@cympfh
Copy link

cympfh commented Sep 20, 2019

008-loop.md の一番最後の factorial 関数の例ですが、

このコードは末尾再帰になっている。

とありますが、なってないように見えます。
私の知ってる末尾再帰は次のようなものです。

int factorial(int n, int acc=1) {
    if (n <= 1) {
        return acc;
    } else {
        return factorial(n - 1, n * acc);
    }
}

// =>
int factorial_loop(int n) {
    int acc = 1;
    while (true) {
        if (n <= 1) {
            return acc;
        }
        acc *= n;
        n--;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant