1+ function calcFactorialRecursive ( input : number ) : number {
2+ if ( input <= 1 ) return 1 ;
3+
4+ return input * calcFactorialRecursive ( input - 1 ) ;
5+ }
6+
7+ function calcFactorialIterative ( input : number ) : number | undefined {
8+ if ( input < 0 ) return undefined ;
9+
10+ let factorial = 1 ;
11+
12+ for ( let i = 2 ; i <= input ; ++ i ) {
13+ factorial *= i ;
14+ }
15+
16+ return factorial ;
17+ }
18+
19+ function validateFactorialInput ( input : number ) : boolean {
20+ return input >= 0 ;
21+ }
22+
23+ function printIterativeFactorial ( input : number ) {
24+ if ( ! validateFactorialInput ( input ) ) {
25+ console . log ( "Input" , input , "is invalid -_-'" ) ;
26+ return ;
27+ }
28+ console . log ( 'Iterative Factorial' , input + ':' , calcFactorialIterative ( input ) ) ;
29+ }
30+
31+ function printRecursiveFactorial ( input : number ) {
32+ if ( ! validateFactorialInput ( input ) ) {
33+ console . log ( "Input" , input , "is invalid -_-'" ) ;
34+ return ;
35+ }
36+ console . log ( 'Recursive Factorial' , input + ':' , calcFactorialRecursive ( input ) ) ;
37+ }
38+
39+
40+ //---------------------------------------------------------------------
41+ // ---------- MAIN PROGRAM ----------
42+ //---------------------------------------------------------------------
43+ if ( import . meta. main ) {
44+
45+ printIterativeFactorial ( 0 ) ;
46+ printIterativeFactorial ( 1 ) ;
47+ printIterativeFactorial ( 2 ) ;
48+ printIterativeFactorial ( 3 ) ;
49+ printIterativeFactorial ( 5 ) ;
50+ printRecursiveFactorial ( 4 ) ;
51+ printRecursiveFactorial ( 0 ) ;
52+ printRecursiveFactorial ( - 1 ) ;
53+ printRecursiveFactorial ( 170 ) ;
54+ printIterativeFactorial ( 171 ) ;
55+
56+ // RUN: deno run Algorithms/Recursion/Factorial.ts
57+ }
58+
59+ // --------------------------- Terminal Output: ---------------------------
60+ // Iterative Factorial 0: 1
61+ // Iterative Factorial 1: 1
62+ // Iterative Factorial 2: 2
63+ // Iterative Factorial 3: 6
64+ // Iterative Factorial 5: 120
65+ // Recursive Factorial 4: 24
66+ // Recursive Factorial 0: 1
67+ // Input -1 is invalid -_-'
68+ // Recursive Factorial 170: 7.257415615307994e+306
69+ // Iterative Factorial 171: Infinity
0 commit comments