File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed
Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change 1+ #[
2+ Factorial in Nim
3+ This program calculates the factorial of a non-negative integer.
4+ ]#
5+
6+ import os
7+ import strutils
8+
9+ const UsageMessage = " Usage: please input a non-negative integer"
10+
11+ proc factorial (n: int ): int =
12+ # Calculates the factorial of n (n!).
13+ if n == 0 :
14+ return 1
15+
16+ var result = 1
17+ for i in 1 .. n:
18+ result *= i
19+
20+ return result
21+
22+ # The main execution block:
23+ block :
24+ # Check 1: No input argument provided.
25+ if paramCount () == 0 :
26+ quit (UsageMessage , 1 )
27+
28+ let inputStr = paramStr (1 )
29+
30+ # Check 2: Invalid Input (Empty String or Not a Number)
31+ var n: int
32+ try :
33+ n = parseInt (inputStr)
34+ except :
35+ quit (UsageMessage , 1 )
36+
37+ # Check 3: Invalid Input (Negative Number)
38+ if n < 0 :
39+ quit (UsageMessage , 1 )
40+
41+ # Print the calculated result.
42+ echo factorial (n)
You can’t perform that action at this time.
0 commit comments