Skip to content

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

@cympfh

Description

@cympfh

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--;
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions