def Factorize(n, primes):
"""
Factorize n by primes.
For every prime p <= sqrt(n), we examine whether n is divided by p. If so, we
compute the maximal integer value e satisfying that n is divided by p^e and n
is not divide by p^{e + 1}.
The factorization is represented by a dict(). It means that all prime factors
of n are not in order. Consider use collections.OrderedDict() instead of
dict() to keep the order of prime factors.
Args:
n: An integer representing a number to be factorized.
primes: An integer list representing all possible prime factors <= sqrt(n).
Returns:
A dictionary where the key representing a prime factor p and the
corresponding value representing the maximal integer value e satisfying that
n is divided by p^e and n is not divide by p^{e + 1}.
"""
factorization = {}
d = n
for prime in primes:
if prime * prime > d:
break
e = 0
while d % prime == 0:
d //= prime
e += 1
if e > 0:
factorization[prime] = e
if d > 1:
factorization[d] = 1
if primes[-1] * primes[-1] < d:
raise ValueError
return factorization
2019年11月1日 星期五
[Python] Factorize code snippet
Factorize code snippet: (depends on GetPrimes())
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言