Update prime_factors.py

Added Benchmark decorator to measure timings for functions primeproduct , prime_factors
This commit is contained in:
Sourabh kumar verma 2023-08-06 21:37:09 +05:30 committed by GitHub
parent 88d939422d
commit f94e08df91
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,9 +1,18 @@
"""
python/black : True
"""
from __future__ import annotations from __future__ import annotations
from math import ceil, sqrt
import time
def timer(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(result)
end = time.time()
print(f"{func.__name__} took {end - start:.6f} seconds to execute.")
return result
return wrapper
@timer
def prime_factors(n: int) -> list[int]: def prime_factors(n: int) -> list[int]:
""" """
Returns prime factors of n as a list. Returns prime factors of n as a list.
@ -46,7 +55,65 @@ def prime_factors(n: int) -> list[int]:
return factors return factors
@timer
def primeproduct(num: int) -> list[int]:
"""
>>> primeproduct(868)
[2, 2, 7, 31]
>>> primeproduct(9039423423423743)
[2, 2, 7, 31, 719, 12572216166097]
>>> primeproduct(0.02)
Traceback (most recent call last):
ValueError: invalid literal for int() with base 10: '0.02'
>>> primeproduct(-2342)
[]
"""
if num <= 1:
return []
prime_factors: list[int] = []
while num > 1:
if len(prime_factors) >= 1 and prime_factors[-1] % num == 0:
prime_factors.append(prime_factors[-1])
else:
sq = ceil(sqrt(num))
flag = 0
if prime_factors != []:
for i in range(prime_factors[-1], sq + 1, 2):
if num % i == 0:
num = num // i
prime_factors.append(i)
flag = 1
break
else:
while num % 2 == 0:
num = num // 2
prime_factors.append(2)
for i in range(3, sq + 1, 2):
if num % i == 0:
num = num // i
prime_factors.append(i)
flag = 1
break
if not flag and num > 1:
prime_factors.append(num)
num = 1
break
return prime_factors
if __name__ == "__main__": if __name__ == "__main__":
n = int(input('enter number: '))
primeproduct(n)
prime_factors(n)
import doctest import doctest
doctest.testmod() doctest.testmod()