你能解释一下这个Factorial函数是如何工作的吗? [英] Can you explain how this Factorial function works?
问题描述
我理解a解决方案是:
function Factorial(number)
{
if(number == 0 || number == 1){
return 1;
}
return number * Factorial(number -1);
}
我想了解到底发生了什么。我理解当数字== 1时,到最后一部分一直在发生什么。
I want to understand what exactly is going on. I understand what is going on all the way to the last part when number == 1.
如果我们采用一个简单的例子说3!
If we were to take a simple example of say 3!
- 3不等于0或1所以我们返回3 * Factorial(2)
- 2不等于到0或1所以我们返回2 * Factorial(1)
- 1等于1所以我们返回1
我们如何知道何时停止?事实是我们返回1告诉函数停止吗?
How do we know when to stop? Is it the fact that we return 1 that tells the function to stop?
如果是这样的话,为什么当我们第一次返回3 * Factorial时函数不会停止( 2)?是因为它返回一个函数,所以它必须继续,直到它不再返回一个函数?
If that is the case, why does the function not stop when we first return 3 * Factorial(2)? Is it because it's returning a function so that it must continue until it no longer returns a function?
谢谢
推荐答案
我认为你必须理解阶乘的逻辑。
I think you have to understand the logic of factorial.
因此,factorial只是产品,用感叹号表示,即如果你写的话
So factorial is just products, indicated by an exclamation mark ie, if you write
0! = 1
1! = 1
2! = 2*1
3! = 3*2*1
4! = 4*3*2*1
5! = 5*4*3*2*1
希望您找到该模式,这样您就可以编写以上阶乘:
Hope you find the pattern, so you can write the above factorials as:
0! = 1
1! = 1
2! = 2*1!
3! = 3*2!
4! = 4*3!
5! = 5*4!
所以在你的函数中你使用的是类似的逻辑。
So in your function you are using the similar logic.
现在你的功能
if(number == 0 || number == 1)
{
return 1;
}
以上逻辑涵盖前两种情况,即 0 !和 1!和
The above logic is to cover the first two cases i.e, 0! and 1! And
return number * Factorial(number -1);
是剩下的数字。
所以你正在使用解决阶乘问题的递归技术。
So you are using the recursive technique of solving the factorial problem.
为了理解递归,让我们取一个数字5即ie,我们想要找到5的值! 。
To understand recursion, lets take a number say 5 i.e., we want find the value of 5!.
然后首先你的函数将检查
Then first your function will check
if(number == 0 || number == 1)
不满足,然后移动到下一行即,
which is not satisfied, then it moves to the next line ie,
return number * Factorial(number -1);
给出
5*Factorial(5-1) which is equal to 5*Factorial(4)
现在,在对您的Factorial函数的后续调用中,它将返回如下值:
Now on subsequent calls to your Factorial function it will return the value like below:
5*(4*Factorial(4-1)) which is equal to 5*(4*Factorial(3))
5*(4*(3*Factorial(3-1)) which is equal to 5*(4*(3*Factorial(2)))
5*(4*(3*(2*Factorial(2-1)))) which is equal to 5*(4*(3*(2*Factorial(1))))
现在当它返回阶乘(1)然后你的状况
Now when it returns factorial(1) then your condition
if(number == 0 || number == 1)
是满意的,因此您得到的结果为:
is satisfied and hence you get the result as:
5*4*3*2*1 = 120
旁注:
请注意,factrial仅用于正整数。
Beware that factrial is used only for positive integers.
这篇关于你能解释一下这个Factorial函数是如何工作的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!