Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Factorial using recursion cpp (#276) #1071

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Factorial using recursion cpp (#276)
  • Loading branch information
anjali7786 committed Mar 15, 2021
commit 045ae9e1fee5dd0465fb10544664b80734904933
46 changes: 34 additions & 12 deletions Code/C++/factorial.cpp
Original file line number Diff line number Diff line change
@@ -1,33 +1,55 @@
/*
Factorial of a non-negative integer, is multiplication of all integers smaller than or equal to n.
Factorial of a positive integer is the product of all integers smaller than or equal to n.
For e.g: n!=1*2*3....*(n-1)*n
Factorial of 0 is 1 i.e 0!=1
*/

#include<iostream>
using namespace std;

int fact(int n){
long long int factorial(int n){
if(n==0)
return 1;
int ans = n*fact(n-1);

return ans;
else if(n==1)
return 1;
else
{
long long int ans = n*factorial(n-1);
return ans;
}
}

int main() {

int main() {
int n;
cin >> n;
cout<<fact(n);
cout<<factorial(n);
return 0;
}

/*
Test case :
Constraint: 0<=n<=20

Test case : 1
Input : 6
Output : 720

Time complexity: O(n)
Space Complexity: O(n)

Test case : 2
Input : 1
Output : 1

Test case : 3
Input : 0
Output : 1

*/

/*
Recurrence Relation:
Base Case: T(n)=1 , n=0
T(n)=T(n-1) + 1 , n>0

Time complexity(T(n)) : O(n)
Space Complexity : O(n)

*/
*/