From fde50e60100de5ba71e510757b607485eae52367 Mon Sep 17 00:00:00 2001 From: Balance-Breaker Date: Tue, 3 Oct 2017 12:44:59 +0530 Subject: [PATCH 1/2] Program for calculating Large Factorial Added --- Misc/LargeFactorial.java | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Misc/LargeFactorial.java diff --git a/Misc/LargeFactorial.java b/Misc/LargeFactorial.java new file mode 100644 index 000000000000..827769329742 --- /dev/null +++ b/Misc/LargeFactorial.java @@ -0,0 +1,32 @@ +import java.util.Scanner; +import java.util.Stack; +class LargeFactorial +{ + public static void main(String []args) + { + Scanner in=new Scanner(System.in); + int n=in.nextInt(); + int x,carry=0; + Stack a=new Stack(); + Stack b=new Stack(); + a.push(1); + for(int i=2;i<=n;i++) + { + while(!a.isEmpty()){ + x=(int)a.pop(); + b.push((x*i+carry)%10); + carry=(x*i+carry)/10;} + while(carry!=0) + { + b.push(carry%10); + carry/=10; + } + while(!b.isEmpty()) + a.push(b.pop()); + } + while(!a.isEmpty()) + b.push(a.pop()); + while(!b.isEmpty()) + System.out.print((int)b.pop()); + } +} From eaf4b59fa8e5b86cd0144ca5d7b6779a8bcbbb5a Mon Sep 17 00:00:00 2001 From: Balance-Breaker Date: Tue, 3 Oct 2017 14:56:56 +0530 Subject: [PATCH 2/2] Comments added --- Misc/LargeFactorial.java | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/Misc/LargeFactorial.java b/Misc/LargeFactorial.java index 827769329742..e228c2a00a56 100644 --- a/Misc/LargeFactorial.java +++ b/Misc/LargeFactorial.java @@ -3,19 +3,24 @@ class LargeFactorial { public static void main(String []args) - { + { + System.out.print("Enter the number whose factorial you want to calculate: "); Scanner in=new Scanner(System.in); int n=in.nextInt(); int x,carry=0; Stack a=new Stack(); Stack b=new Stack(); - a.push(1); - for(int i=2;i<=n;i++) + a.push(1);//Initialize stack with value '1' + for(int i=2;i<=n;i++)//Running loop only for n>1 else give output '1' { - while(!a.isEmpty()){ + while(!a.isEmpty())//Loop will run until stack a is not empty + { x=(int)a.pop(); b.push((x*i+carry)%10); + //Getting digit from stack a and multipling with i and pushing its unit digit to stack b + // And storing its carry that can be added to next position in stack carry=(x*i+carry)/10;} + //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 while(carry!=0) { b.push(carry%10); @@ -24,9 +29,12 @@ public static void main(String []args) while(!b.isEmpty()) a.push(b.pop()); } + + //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 while(!a.isEmpty()) b.push(a.pop()); while(!b.isEmpty()) + //Printing the content of stack b System.out.print((int)b.pop()); } }