-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathlab7.java
More file actions
130 lines (128 loc) · 3.32 KB
/
lab7.java
File metadata and controls
130 lines (128 loc) · 3.32 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
//Mehak Gupta
//2016163
public class lab7 {
//implementation of stack data type
static class stack {
int length = 3000;
int top = -1 ;
int[] arr;
stack(){
arr = new int[length];
}
void push(int n){
top ++;
arr[top] = n;
}
int pop(){
int x = arr[top];
top--;
return x;
}
int peek(){
return arr[top];
}
}
//add two numbers using stack
static stack add(stack a , stack b){
stack c = new stack();
int z;
int carry =0;
while (a.top >-1 && b.top >-1){
z = a.pop() + b.pop() + carry ;
c.push(z%10);
carry = z/10;
}
if (a.top >= 0){
int h=0;
while (a.top>-1){
h = a.pop()+ carry;
c.push(h%10);
carry = h/10;
}
}
if (b.top >= 0){
int h = 0 ;
while(b.top > -1){
h = b.pop() + carry;
c.push(h%10);
carry = h/10;
}
}
if(carry!=0)
c.push(carry);
stack d = new stack();
while(c.top>-1){
int o = c.pop();
d.push(o);
}
return d;
}
static stack mult(stack a , stack b){
stack temp = new stack();
stack ans = new stack();
stack p = new stack();
int c;
int g = b.top;
for (int i =0;i<=g;i++){
stack d =new stack();
c = b.pop();
for (int l=0;l<i;l++){
d.push(0);
}
int e;
int m;
int carry =0;
int t = a.top;
for (int z=0;z<=a.top;z++){
p.push(a.arr[z]);
}
for (int j=0;j<=t;j++){
e = p.pop();
m = e * c + carry;
d.push(m%10);
carry = m/10;
}
if (carry !=0){
d.push(carry);
}
while (d.top >-1){
int f = d.pop();
ans.push(f);
}
temp = add(temp , ans);
}
return temp;
}
static void factorial() throws IOException{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int input = Integer.parseInt(reader.readLine());
stack a = new stack();
stack c = new stack();
stack d = new stack();
a.push(1);
for (int i=2;i<=input;i++){
stack b = new stack();
int j=i;
while(j>0){
b.push(j%10);
j=j/10;
}
while(b.top>-1){
int h = b.pop();
c.push(h);
}
a = mult(a , c);
}
while (a.top>-1){
int l = a.pop();
d.push(l);
}
while(d.top >-1){
System.out.print(d.pop());
}
}
public static void main(String[] args) throws IOException{
factorial();
System.out.println();
}
}