Compare commits

...

2 Commits

2 changed files with 23 additions and 6 deletions

View File

@ -1,12 +1,20 @@
import math
def factorial(n: int) -> int:
def factorial(n: int, start: int = 1) -> int:
"""
n! = 1 * 2 * 3 * 4 * ... * n
1, 1, 2, 6, 24, 120, 720, ...
If you're looking for efficiency with start == 1, just use math.factorial(n)
which takes just 25% of the compute time on average, but this is the fastest
pure python implementation I could come up with and it allows for partial
multiplications, like 5 * 6 * 7 * 8 * .... * 17
"""
return math.factorial(n)
if start == n:
return n
if n - start == 1:
return n * start
middle = start + (n - start) // 2
return factorial(middle, start) * factorial(n, middle + 1)
def fibonacci(n: int) -> int:
@ -38,3 +46,10 @@ def pentagonal(n: int) -> int:
0, 1, 5, 12, 22, 35, ...
"""
return ((3 * n * n) - n) // 2
def hexagonal(n: int) -> int:
if n == 1:
return 1
return n * 2 + (n - 1) * 2 + (n - 2) * 2 + hexagonal(n - 1)

View File

@ -20,7 +20,9 @@ class StopWatch:
self.stopped = perf_counter_ns()
self.total_elapsed += self.elapsed()
reset = start
def reset(self):
self.total_elapsed = 0
self.start()
def elapsed(self) -> int:
if self.stopped is None: