def get_prime_factors(num: int, prime_list: list = None) -> list: """Returns a list of tuples containing prime factors and their multiplicty To speed up repeated calculations, can optionally pass in a list of primes which will be used to generate the list of prime factors. >>> get_prime_factors(12) [(2, 2), (3, 1)] >>> get_prime_factors(14) [(2, 1), (7, 1)] >>> get_prime_factors(2) [(2, 1)] >>> get_prime_factors(4) [(2, 2)] """ upper_bound = math.ceil(num / 2) + 1 if not prime_list: prime_list = [prime for prime in primes.Primes(upper_bound)] prime_factors = [] for prime in prime_list: temp = num multiplicity = 0 temp, remainder = divmod(temp, prime) while remainder == 0 and temp >= 1: multiplicity += 1 temp, remainder = divmod(temp, prime) if multiplicity > 0: prime_factors.append((prime, multiplicity)) if prime > upper_bound: break if not prime_factors: prime_factors = [(num, 1)] return prime_factors
def test_in_primes(): primes_under_ten = primes.Primes(10) assert 3 in primes_under_ten assert 4 not in primes_under_ten
def test_len_primes(): primes_under_ten = primes.Primes(10) assert len(primes_under_ten) == 4
def test_largest_prime(): primes_under_thousand = primes.Primes(10**3) largest_prime_under_thousand = primes_under_thousand.largest_prime() assert largest_prime_under_thousand == 997
def test_reversed_primes(): primes_under_ten = primes.Primes(10) primes_under_ten_reversed = [prime for prime in reversed(primes_under_ten)] assert primes_under_ten_reversed == [7, 5, 3, 2]
def test_iter_primes(): primes_under_ten = primes.Primes(10) primes_under_ten_list = [prime for prime in primes_under_ten] assert primes_under_ten_list == [2, 3, 5, 7]