factorial

This commit is contained in:
Rohit Tanwar
2018-01-27 11:01:18 +05:30
parent 2bcb100b85
commit 94a4c53868
3 changed files with 35 additions and 1 deletions

View File

@ -12,6 +12,7 @@
### :heavy_division_sign: Math
<details><summary>View contents</summary> <ul><li><a href = "#average"><code>average</code></a></li>
<li><a href = "#factorial"><code>factorial</code></a></li>
<li><a href = "#gcd"><code>gcd</code></a></li>
<li><a href = "#lcm"><code>lcm</code></a></li>
<li><a href = "#max_n"><code>max_n</code></a></li>
@ -68,6 +69,34 @@ average(1, 2, 3) # 2.0
<br><a href = "#table-of-contents">:arrow_up: Back to top</a>
### 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.
```py
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)
```
<details><summary>View Examples</summary>
```py
factorial(6) # 720
```
</details>
<br><a href = "#table-of-contents">:arrow_up: Back to top</a>
### gcd
:information_source: `math.gcd` works with only two numbers

View File

@ -6,10 +6,14 @@ Use recursion. If `num` is less than or equal to `1`, return `1`. Otherwise, ret
```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)
```
```
``` python
factorial(6) # 720
```

View File

@ -5,6 +5,7 @@ count_occurences:list
count_vowels:string
deep_flatten:list
difference:list
factorial:math
gcd:math
lcm:math
max_n:math