The factorial function is a mathematical formula represented by an exclamation mark "!". In the Factorial formula you must multiply all the integers and positives that exist between the number that appears in the formula and the number 1.
"the factorial of any number is that number times the factorial of (that number minus 1)"
Here’s an example:
5! = 1 * 2 * 3 * 4 * 5 = 120On this formula number 5 will be called 5th factorial and multiplied by all the numbers that appear on the example until number 1.
Calculating From the Previous Value (Recursive Program)
We can easily calculate a factorial from the previous factorial valueTo work out 5!, multiply 5 by 4! to get 120 here 4! = 1*2*3*4 = 24So the rule is:
To work out 4!, multiply 4 by 3! to get 24 here 3! = 1*2*3 = 6
To work out 3!, multiply 3 by 2! to get 6 here 2! = 1*2 = 2
To work out 2!, multiply 2 by 1! to get 2 here 1! = 1
To work out 1!, multiply 1 by 0! to get 1 here 0! = 1
n! = n × (n−1)!Which says
"the factorial of any number is that number times the factorial of (that number minus 1)"
So 7! = 7 × 6!, ... and 123! = 123 × 122!, etc.
Example: C++ program to find factorial
For loop runs from 1 to n. For each iteration of the loop, factorial is multiplied with i. Then the final value of factorial is the product of all numbers from 1 to n.Output
Enter a positive integer: 5
Factorial of 5 is 120
Example: C++ program to find factorial using a function
For loop runs from 1 to n. For each iteration of the loop, factorial is multiplied with i. Then thefinal value of factorial is the product of all numbers from 1 to n.Output
Enter a positive integer: 5
Factorial of 5 is 120
Example: C++ program to find factorial using a Recursive Program
If the number is 0 or 1 then factorial() returns 1. If any other number, then factorial() recursively calls itself with the value n-1 i.e factorial(n-1).Output
Enter a positive integer: 5
Factorial of 5 is 120
Post a Comment
Thank you for vising