#include <iostream>
using namespace std;
int main()
{
int i,fact=1,number;
cout<<"Enter any Number: ";
cin>>number;
for(i=1;i<=number;i++){
fact=fact*i;
}
cout<<"Factorial of " <<number<<" is: "<<fact<<endl;
return 0;
}
#include <cmath>
int fact(int n){
return std::tgamma(n + 1);
}
// for n = 5 -> 5 * 4 * 3 * 2 = 120
//tgamma performas factorial with n - 1 -> hence we use n + 1
/*#include<bits/stdc++.h>
using namespace std;
iterative solution:
int fact (int n, int k)
{
if(n==0) return 1;
return fact(n-1,k*n);
}
int main()
{
int n,k=1;
cin>>n;
int ans=fact(n,k);
cout<<ans<<endl;
}*/
//recursive solution.
#include<bits/stdc++.h>
using namespace std;
int fact(int n)
{
if(n==0)return 1;
return n*fact(n-1);
}
int main(){
int n;
cin>>n;
cout<<fact(n)<<endl;
}
int factorial(int n)
{
return (n == 1 || n == 0) ? 1 : factorial(n - 1) * n;
}
#include<iostream>
using namespace std;
int factorial(int x){
if(x==0){ // Base-case ( VERY IMPORTANT)
return(1);
}
else{
return(x*(factorial(x-1))) ;
}
}
int main(){
int no = 5;
cout << factorial(no) ; // 120
}
#include<iostream>
using namespace std;
int main(){
int no = 5;
int factorial = 1;
for(int a=no;a>0;--a){ //note: decrement(--)
factorial *= a ; // note(*=)
}
cout << factorial ; // 120
}
#include<bits/stdc++.h>
using namespace std;
#define ll long long
ll fact(ll a){
ll ans = 1;
ll curr = 1;
while(a--){
ans *= curr;
curr++;
}
return ans;
}
int main(){
int x;
cin >> x;
cout << fact(x) ;
}
Code Example |
---|
Cpp :: C++ Volume of a Cylinder |
Cpp :: vector::insert |
Cpp :: how to use cout function in c++ |
Cpp :: how to sort in c++ |
Cpp :: sqrt in c++ |
Cpp :: c++ thread incide class |
Cpp :: team fortress |
Cpp :: c++ casting |
Cpp :: reverse order binary tree in c++ |
Cpp :: c++ create thread |
Cpp :: c++ min int |
Cpp :: std vector random shuffle |
Cpp :: memory leak in cpp |
Cpp :: last character of std::string |
Cpp :: remove element from vector |
Cpp :: how to use toString method in C++ |
Cpp :: how to initialize vector |
Cpp :: c++ initialize a vector |
Cpp :: c++ compile to exe command line |
Cpp :: constructor in cpp |
Cpp :: linked list in c++ |
Cpp :: c++ move semantics for `this` |
Cpp :: How to turn an integer variable into a char c++ |
Cpp :: define vector with size and value c++ |
Cpp :: c++ read matttrix from text file |
Cpp :: how to declare a vector of int in c++ |
Cpp :: ue4 c++ replicate actor variable |
Cpp :: c++ remove all elements equal to |
Cpp :: matrix c++ |
Cpp :: sliding window c++ |