File tree Expand file tree Collapse file tree 1 file changed +12
-4
lines changed Expand file tree Collapse file tree 1 file changed +12
-4
lines changed Original file line number Diff line number Diff line change 3
3
class LargeFactorial
4
4
{
5
5
public static void main (String []args )
6
- {
6
+ {
7
+ System .out .print ("Enter the number whose factorial you want to calculate: " );
7
8
Scanner in =new Scanner (System .in );
8
9
int n =in .nextInt ();
9
10
int x ,carry =0 ;
10
11
Stack a =new Stack ();
11
12
Stack b =new Stack ();
12
- a .push (1 );
13
- for (int i =2 ;i <=n ;i ++)
13
+ a .push (1 );//Initialize stack with value '1'
14
+ for (int i =2 ;i <=n ;i ++)//Running loop only for n>1 else give output '1'
14
15
{
15
- while (!a .isEmpty ()){
16
+ while (!a .isEmpty ())//Loop will run until stack a is not empty
17
+ {
16
18
x =(int )a .pop ();
17
19
b .push ((x *i +carry )%10 );
20
+ //Getting digit from stack a and multipling with i and pushing its unit digit to stack b
21
+ // And storing its carry that can be added to next position in stack
18
22
carry =(x *i +carry )/10 ;}
23
+ //Now if any carry is left to be added to sstack will be now added this step is the main step increasing the nnumber of digit in the number
19
24
while (carry !=0 )
20
25
{
21
26
b .push (carry %10 );
@@ -24,9 +29,12 @@ public static void main(String []args)
24
29
while (!b .isEmpty ())
25
30
a .push (b .pop ());
26
31
}
32
+
33
+ //Stack a containg Least significant digit on the top and Most significant Digit on the bottom so reversing it in stack b to print the result
27
34
while (!a .isEmpty ())
28
35
b .push (a .pop ());
29
36
while (!b .isEmpty ())
37
+ //Printing the content of stack b
30
38
System .out .print ((int )b .pop ());
31
39
}
32
40
}
You can’t perform that action at this time.
0 commit comments