Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
686 views
in Technique[技术] by (71.8m points)

javascript - Can you explain how this Factorial function works?

I understand that "a" solution is:

function Factorial(number)
{
    if(number == 0 || number == 1){
        return 1;
    }

    return number * Factorial(number -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.

If we were to take a simple example of say 3!

  1. 3 is not equal to 0 or 1 so we return 3 * Factorial(2)
  2. 2 is not equal to 0 or 1 so we return 2 * Factorial(1)
  3. 1 is equal to 1 so we return 1

How do we know when to stop? Is it the fact that we return 1 that tells the function to stop?

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?

Thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you have to understand the logic of 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.

Now in your function

if(number == 0 || number == 1)
{
   return 1;
}

The above logic is to cover the first two cases i.e, 0! and 1! And

return number * Factorial(number -1);

is for the rest of the numbers.

So you are using the recursive technique of solving the factorial problem.

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

which gives

5*Factorial(5-1) which is equal to 5*Factorial(4)

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

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

On a side note:

Beware that factrial is used only for positive integers.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...