mirror of
https://git.adityakumar.xyz/data-structures.git
synced 2024-11-21 17:32:53 +00:00
add factorial
This commit is contained in:
parent
1c45c1a9c9
commit
719e7dab9b
1 changed files with 19 additions and 0 deletions
19
java/Stack/factorial.java
Normal file
19
java/Stack/factorial.java
Normal file
|
@ -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<Integer> S = new AStack<Integer>(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));
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue