2017-08-24 11 views
-3

だから、友人は階乗について私にこのコードを共有しました。そして、私は、ループを通らない正しい結果をどのように提供するのか苦労しています。私が5歳のように誰かが私にそれを説明することができたら、私は本当にそれを感謝します。誰かがこのコードの仕組みを私に説明できますか?

function fact(n){ 
    if(n === 1){ 
    return 1; 
    }else{ 
    return n * fact(n - 1); 
    }; 
}; 
console.log(fact(5)); 
+3

あなたのGoogleキーワードは「再帰」です –

+0

ループを使用しています。再帰的です。再帰の作業を参照してください。この* exact *コードはこれまで何度も説明されてきました。 – Carcigenicate

+3

あなたの友人はそれをあなたや何かに説明することを拒否していますか? – BoltClock

答えて

0

。 !

function factorial(n) { 
    return (n != 1) ? n * factorial(n - 1) : 1; 
} 

alert(factorial(5)); // 120 

再帰的に値1そして、あなたです:nの関数の結果は、nがn-1ために関数の結果を掛けたとして得られる、というように1にすることができ、ある そして、コードが少し短くなり基礎と0を作ることができる:

function factorial(n) { 
    return n ? n * factorial(n - 1) : 1; 
} 

alert(factorial(5)); // 120 

この場合、コールfactorial (1)1 * factorial (0)に低減され、再帰の追加のステップがあるでしょう。

0

コードは、数値の階乗を求める再帰関数呼び出しです。

function fact(n){ // function declaration 
    if(n === 1){ //strict type check if n is an integer 1 not a '1' 
    return 1; // return back 1 
    }else{ // if n is not 1 
    return n * fact(n - 1); //return the number n multiplied by the function call fact again in which the parameter is n-1 now. 
    }; 
}; 
console.log(fact(5)); //print the result of function call fact(5) and print it to console. 

function fact(n){ 
 
    if(n === 1){ 
 
    return 1; 
 
    }else{ 
 
    return n * fact(n - 1); 
 
    }; 
 
}; 
 
console.log(fact(5));

これは、階乗を計算する数式上で動作する呼び出しです:n!n * (n-1) !のように書くことができます、階乗の特性に

n * (n-1) ! 
0

再帰に関しては、それを自分自身を呼び出す関数と考えることができます。あなたは事実を呼び出すときに、この場合

function fact(n){ 
    //test to see if n is 1, if so just return 1 
    if(n === 1) 
     return 1; 
    // multiply n by the result of calling fact(n-1) 
    return n * fact(n - 1); 
} 

console.log(fact(5)); 

にので、この場合には(5) あなたは 5 *実際(5-1)= 4 *実際(4-1)= 3 *事実になるだろう(3 - 1)で得られた2 *事実(2-1)= 1

を= 5×4×3×2×1 = 120

それは、挿入概念のトリッキーが最初に把握するビット試すいconsole.logを関数に追加すると、何が起こっているのかをより明確に把握できます。

function fact(n){ 
    console.log(n); 
    //test to see if n is 1, if so just return 1 
    if(n === 1) 
     return 1; 
    // multiply n by the result of calling fact(n-1) 
    return n * fact(n - 1); 
} 
+0

ありがとう、それはより明確な説明でした。感謝します。 – Nar

+0

私は再帰について言及すべきではない根本的なことは、すべての再帰関数は終了条件を必要とするということです。この例では(n === 1)return 1です。この出口条件がなければ、あなたは無限ループに陥ります。 – Pav

関連する問題