Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sys
- import unicodedata
- from math import floor
- from math import log
- from math import sqrt
- from typing import List
- from typing import Tuple
- class prime_iterable:
- def __init__(self):
- self._memoized = [2, 3]
- def _gen_primes(self):
- sentinel = 0
- for sentinel in self._memoized:
- yield sentinel
- while True:
- sentinel += 2
- if self.is_prime(sentinel):
- self._memoized.append(sentinel)
- yield sentinel
- @staticmethod
- def is_prime(n):
- for candidate in range(2, floor(sqrt(n)) + 1):
- if n % candidate == 0:
- return False
- return True
- def __call__(self, end, start=1):
- for prime in self._gen_primes():
- if prime <= start:
- continue
- elif prime >= end:
- break
- yield prime
- primes = prime_iterable()
- def factorize(n: int) -> List[Tuple[int, int]]:
- factors: List[Tuple[int, int]] = []
- factorized = n
- for candidate_m in primes(n - 1):
- if factorized == 1:
- break
- elif candidate_m > factorized:
- raise ValueError(f"No prime factorization found for {n}")
- if factorized % candidate_m == 0:
- for candidate_e in range(1, floor(log(factorized, candidate_m)) + 2):
- if factorized % (candidate_m ** (candidate_e)) != 0:
- candidate_e -= 1
- factors.append((candidate_m, candidate_e))
- factorized = factorized // (candidate_m ** candidate_e)
- break
- else:
- factors = [(n, 1)]
- return factors
- def superscript(n: int) -> str:
- return "".join(
- unicodedata.lookup(unicodedata.name(digit).replace("DIGIT", "SUPERSCRIPT"))
- for digit in str(n)
- )
- if __name__ == "__main__":
- try:
- factorands = map(int, sys.argv[1:])
- for factorand in factorands:
- factors = factorize(factorand)
- factor_string = " × ".join(
- f"{mantissa}{superscript(exponent)}" for mantissa, exponent in factors
- )
- print(f"{factorand} = {factor_string}")
- except (ValueError, IndexError):
- print(
- f"Usage: {sys.argv[0]} number_to_be_factored [other_number_to_be_factored ...]",
- file=sys.stderr,
- )
Add Comment
Please, Sign In to add comment