Update prime_factorization_fast.py

This commit is contained in:
Sourabh kumar verma 2023-08-22 00:11:53 +05:30 committed by GitHub
parent 332f34cba3
commit b64348256f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,37 +1,9 @@
from __future__ import annotations from __future__ import annotations
from math import ceil, sqrt from math import ceil, sqrt
import time
from typing import Any from typing import Any
def timer(func: callable) -> callable: def prime_factors(num: int) -> list[int]:
"""
Decorator that measures the execution time of a function.
:param func: The function to be timed.
:return: The wrapped function.
"""
def wrapper(*args: Any, **kwargs: Any) -> Any:
"""
Wraps the given function and measures its execution time.
:param args: Positional arguments for the function.
:param kwargs: Keyword arguments for the function.
:return: The result of the wrapped function.
"""
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} took {end - start:.6f} seconds to execute.")
return result
return wrapper
@timer
def prime_factors(number: int) -> list[int]:
""" """
Returns prime factors of a given number as a list. Returns prime factors of a given number as a list.
Returns prime factors of n as a list. Returns prime factors of n as a list.
@ -63,18 +35,17 @@ def prime_factors(number: int) -> list[int]:
""" """
i = 2 i = 2
factors = [] factors = []
while i * i <= number: while i * i <= num:
if number % i: if num % i:
i += 1 i += 1
else: else:
number //= i num //= i
factors.append(i) factors.append(i)
if number > 1: if num > 1:
factors.append(number) factors.append(num)
return factors return factors
@timer
def primeproduct(num: int) -> list[int]: def primeproduct(num: int) -> list[int]:
""" """
Returns prime factors of a positive integer num as a list. Returns prime factors of a positive integer num as a list.
@ -82,10 +53,9 @@ def primeproduct(num: int) -> list[int]:
>>> primeproduct(868) >>> primeproduct(868)
[2, 2, 7, 31] [2, 2, 7, 31]
>>> primeproduct(9039423423423743) >>> primeproduct(9039423423423743)
[2, 2, 7, 31, 719, 12572216166097] [7, 719, 1796030880871]
>>> primeproduct(0.02) >>> primeproduct(435345234543252)
Traceback (most recent call last): [2, 2, 3, 3, 3, 11, 3119, 5171, 22721]
ValueError: invalid literal for int() with base 10: '0.02'
>>> primeproduct(-2342) >>> primeproduct(-2342)
[] []
@ -131,11 +101,9 @@ def primeproduct(num: int) -> list[int]:
if __name__ == "__main__": if __name__ == "__main__":
n = int(input("enter number: ")) n = int(input("enter number: ").strip())
primeproduct(n) primeproduct(n)
prime_factors(n) prime_factors(n)
import doctest import doctest
doctest.NORMALIZE_WHITESPACE
doctest.testmod() doctest.testmod()