forked from 7harshit20/dsa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfactorial.cpp
70 lines (67 loc) · 1.68 KB
/
factorial.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include<iostream>
#include<vector>
using namespace std;
void swap(int* a,int *b){
int temp=*a;
*a=*b;
*b=temp;
}
void reverse(vector<int> &v,int a,int b){
for(int i=0;i<=(b-a)/2;i++){
swap(&v[a+i],&v[b-i]);
}
}
vector<int> factorial(int N){
// code here
vector<int> v;
v.push_back(1);
for(int i=1;i<=N;i++){
int carry=0;
for(int j=v.size()-1;j>=0;j--){
int dig =v[j];
v[j]= ((dig*i)+ carry)%10;
carry= (dig*i+ carry)/10;
if(j==0 && carry!=0){
int k=v.size()-1;
while(carry!=0){
v.push_back(carry%10);
carry/=10;
}
reverse(v,0,k);
reverse(v,0,v.size()-1);
}
}
}
return v;
}
vector<int> factorial2(int N){
// code here
vector<int> v;
v.push_back(1);
for(int i=1;i<=N;i++){
int carry=0;
int k=v.size();
for(int j=0;j<k;j++){
int dig =v[j];
v[j]= ((dig*i)+ carry)%10;
carry= (dig*i+ carry)/10;
if(j==v.size()-1 && carry!=0){
while(carry!=0){
v.push_back(carry%10);
carry/=10;
}
}
}
}
reverse(v,0,v.size()-1);
return v;
}
int main(){
int n;
cin>>n;
vector<int> v;
v=factorial(n);
for(auto ele:v)
cout<<ele;
return 0;
}