Skip to content

Instantly share code, notes, and snippets.

@pavdmyt
Created October 1, 2015 16:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pavdmyt/3b99e9b499289e072a48 to your computer and use it in GitHub Desktop.
Save pavdmyt/3b99e9b499289e072a48 to your computer and use it in GitHub Desktop.
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