![]() There are tons of applications when it comes to using a factorial. Then the final factorial value of the number is returned. The recursive calls are made till we reach a value whose factorial value is already known, i.e., either 0 or 1, from where the values are calculated. If the value of num is greater than 1, then a similar recursive call is made, as we have already seen and understood above. In the given code below, we can see that if the value of ‘num’ is 0 or 1, the first expression becomes true, and value 1 is returned. if else įirst, we write the work to be done when the expression is true, and then we write the work to be done in the else case, i.e., when the first expression is false. ![]() In a ternary statement, the format is like this: In the following programs, we will use the same recursive code that we have seen above, the difference being that instead of the if-else conditional statement, we will use the ternary operator in Python, which is also a type of conditional statement. ValueError: invalid literal for int() with base 10: 'Ram' ![]() Finally, using the answer found at each step, we will calculate our final answer, i.e., factorial of N.įor N 0, factorial(N) = N * factorial(N-1) ![]() Now, (N-1) factorial will make a call on (N-2) factorial to get the answer, and this will go on until we reach 0 i.e. ![]() We can also see that in recursion, we will call for (N-1) factorial, and assuming that answer is correct, we will calculate the answer for N factorial. for all positive values.įor N = 0, we already know that 0! = 1, this condition will be the base case in our recursion code. Algorithm for the Factorial Program in Pythonįor any number N greater than 0, we can write: ![]()
0 Comments
Leave a Reply. |