Few ways to calculate factorial of the number.
""" | |
Few ways to calculate factorial of the number. | |
For my article: http://pavdmyt.com/digging-around-factorial-function/ | |
""" | |
import math as m | |
def fact(x): | |
""" | |
Weird factorial function implementation | |
by hypothetical mathematician. | |
""" | |
return m.exp(sum([m.log(k) for k in range(1, x+1)])) | |
def iterative_fact(x): | |
""" | |
Common iterative factorial function. | |
""" | |
res = 1 | |
for i in range(2, x + 1): | |
res *= i | |
return res | |
def fast_fact(x): | |
""" | |
Calculates factorial of the number faster. | |
""" | |
if x % 2: | |
res = x | |
x -= 1 | |
else: | |
res = 1 | |
i = 0 | |
nums = range(x, 0, -2) | |
for num in nums: | |
i += num | |
res *= i | |
return res | |
if __name__ == '__main__': | |
# Tests. | |
import unittest | |
class Test(unittest.TestCase): | |
def test_iterative_fact(self): | |
for num in range(30): | |
self.assertEqual(iterative_fact(num), m.factorial(num)) | |
def test_fast_fact(self): | |
for num in range(30): | |
self.assertEqual(fast_fact(num), m.factorial(num)) | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment