2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

再帰関数を使って階乗を求める関数を作る

Last updated at Posted at 2018-07-31

再帰関数とは

ある関数が自分自身を呼び出す事。
または、そのような関数。

例えば、階乗を計算するように、同種の手続きをなんども呼び出すような処理をコンパクトに表現できる。

例えば

引数の数字の階乗を求める関数を例とします。
階乗とは、総積のこと。
例えば5なら、 5 * 4 * 3 * 2 * 1 =120

自然数nの階乗は
n * (n-1の階乗)
で求められるので、それを元にコードを書くと


function factorial(n) {
  if(n != 0) {
    return n * factorial(n - 1);
  }
  return 1;
}

結果はこう

console.log(factorial(5));
// 結果は120

factorial()の中で、factorial()を呼び出している。

2
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?