From 2bcb100b85f05e7635c59f2b721f1f31068919ad Mon Sep 17 00:00:00 2001 From: Rohit Tanwar Date: Sat, 27 Jan 2018 10:59:56 +0530 Subject: [PATCH] factorial --- snippets/factorial.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 snippets/factorial.md diff --git a/snippets/factorial.md b/snippets/factorial.md new file mode 100644 index 000000000..bb801131d --- /dev/null +++ b/snippets/factorial.md @@ -0,0 +1,15 @@ +### factorial + +Calculates the factorial of a number. + +Use recursion. If `num` is less than or equal to `1`, return `1`. Otherwise, return the product of `num` and the factorial of `num - 1`. Throws an exception if `num` is a negative or a floating point number. + +```python + +def factorial(num): + if not ((num >= 0) & (num % 1 == 0)): + raise Exception( + f"Number( {num} ) can't be floating point or negative ") + return 1 if num == 0 else num * factorial(num - 1) + +``` \ No newline at end of file