Factorial is the product of all the numbers starting from 1 till the given number.
For example: Factorial of 5 will be = 1*2*3*4*5 = 120
Note: Factorial of a negative number doesn’t exist. And, the factorial of 0 is 1.
Methods:
- Naïve approach
- Using Recursion
Method 1: Naïve approach
Logic:
Factorial of a non-negative integer x is the multiplication of all the integers smaller than or equal to x.
Algorithm:
- Take input.
- Initialize a variable to store product of numbers.
- Run a for loop which runs from 1 till the given number.
- Multiply each number with the fact variable.
- Print the output.
Code:
#include<iostream>
using namespace std;
int main()
{
int n,fact=1;
cout<<"Enter number";
cin>>n;
for(int i=1;i<=n;i++)
fact=fact*i;
cout<<"\n Factorial of given number is:"<<fact;
return 0;
}
Output:
Enter number: 6
Factorial of given number is:720
Method 2: Using function
Logic:
The same logic is used as above but here we are using function.
Algorithm:
- Take input.
- Initialize a variable to store product of numbers.
- Run a for loop which runs from 1 till the given number.
- Call the function with fact and number as a parameter.
- Store the returned value in fact variable.
- Print the output.
Code:
#include<iostream>
using namespace std;
int factorial(int fact,int n)
{
fact=fact*n;
return fact;
}
int main()
{
int n,fact=1;
cout<<"Enter number";
cin>>n;
for(int i=1;i<=n;i++)
fact=factorial(fact,i);
cout<<"\n Factorial of given number is:"<<fact;
return 0;
}
Output:
Enter number: 7
Factorial of given number is: 5040
Report Error/ Suggestion