Skip to content

Commit b274425

Browse files
authored
Add Factorial in Nim (#5187)
1 parent b976ecf commit b274425

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

archive/n/nim/factorial.nim

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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)

0 commit comments

Comments
 (0)