From 719e7dab9b56fe71bfb2cc7f58165164a9bf767e Mon Sep 17 00:00:00 2001 From: Aditya Date: Tue, 13 Sep 2022 19:15:43 +0530 Subject: [PATCH] add factorial --- java/Stack/factorial.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 java/Stack/factorial.java diff --git a/java/Stack/factorial.java b/java/Stack/factorial.java new file mode 100644 index 0000000..c874535 --- /dev/null +++ b/java/Stack/factorial.java @@ -0,0 +1,19 @@ +class factorial { + /** @return n! */ + static long fact(int n) { + // To fit n! in a long variable, require n < 21 + assert (n >= 0) && (n <= 20) : "n out of range"; + // Make a stack just big enough + Stack S = new AStack(n); + while (n > 1) S.push(n--); + long result = 1; + while (S.length() > 0) + result = result * S.pop(); + + return result; + } + + public static void main(String[] args) { + System.out.println(fact(5)); + } +}