LoginSignup
1
1

More than 5 years have passed since last update.

Bonfire: javascriptでfactorializationメモ

Last updated at Posted at 2015-12-14

またまたFreecodecampのbonfire課題より。

/*
Return the factorial of the provided integer.
If the integer is represented with the letter n, a factorial is the product of all positive integers less than or equal to n.
Factorials are often represented with the shorthand notation n!
*/

function factorialize(num) {
  return num;
}

factorialize(5);

最初はif elsefor loopを使ってこんな感じで書いていた。

function factorialize(num) {
    var count = num;
    if (num === 0) {
        return 1;
    }
    else {
        for (var i = 1; i < count; i++){
            num = num * i;
        }
    }
    return num; //120
}

factorialize(5)

処理毎に変数iの値を繰り上げていくのだがnumは処理毎に数値が変わってしまうので別のplaceholderとしてcountを用意。iを1から初めてi === count(5)になるまでnum = num * 1i++処理を繰り返して下さいってこと。

// こんな感じで行われている

// initially...num = 5, i = 1

5 x 1 = 5 // num = 5, i = 2 < count
5 x 2 = 10 // num = 10, i = 3 < count
10 x 3  = 30 // num = 30, i = 4 < count
30 x 4 = 120 // num = 120, i = 5 = count // stops here

その後も色々模索した結果、

function factorialize(num) {
  if (num === 0) {
    return 1;
  }
  else {
    return num * factorialize(num -1);
  }
}

factorialize(5); // 120

あえてnum * factorialize(num - 1);とすることで先にnum全ての値を出してから最後にまとめて掛け合わせる。
for loopを消して少しだけシンプルにしてみました。

1
1
0

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
1
1