# 5 - Factorial - Solved

#1

alright, so this is the working code, but for anyone who was curious i wanted to explain WHY this code worked lol. I got stuck on this for about an hour (sad, i know) but i didnt want to look at the Q&A because i knew i wouldnt learn anything by doing that. so anyways, it took me forever but i figured it out. (ps, this explanation sucks because its hard to explain XD)

you have to write the IF statement because it needs to check if the number is 1, for multiple reasons. the first being that if x is 1, then the answer is one.

the second part of the code is taking every number in the range of x and subtracting 1 and then multiplying them all together.

so say "x" was 4

the code is going to go through this process:
does 4 equal 1?
no, so lets move on to the ELSE statement
4 * factorial(4-1)
-which would be 4*3
so thats one of the factorials
and then it goes through it again because it called the factorial function again.
and since 3 doesnt equal 1 it will run the code again.
this time it would be 3-1
which equals 2

it goes through it until it reaches one.

back to the other reasons, if it didnt have that first part of the if statement, it would go on forever since the function calls itself, this statement makes sure its not an infinite loop and gives it a stopping point and then also if if you subtracted 1 from 1 it would be 0 and anything you multiply by 0 is 0 and then no matter what number you put in there it would return 0

#2

Is there anything you would like help with, Or is this strictly an informational Topic? Congratz by the way

#3

informational for anyone that struggled with this as i did haha

#4

I'm a little concerned (minor) that there are two terms distinctly notable by their absence from the above discourse:

1. Recursion
2. Call stack

Also, we don't see the terms, `base case` or `recursive case`. In a discussion such as this, we should not only solve our own problem, but when giving advice, research so that our explanation is more in line with the topic diction (words and terms). Never be afraid to work on a second draft if you find ways to improve your writing.