【发布时间】:2011-04-08 07:23:25
【问题描述】:
我正在研究一个需要对整数进行因式分解的 Project Euler 问题。我可以列出作为给定数字因子的所有素数的列表。算术基本定理意味着我可以使用这个列表推导出数字的每个因数。
我目前的计划是获取基素数列表中的每个数字并提高其幂,直到它不再是整数因子,才能找到每个素数的最大指数。然后,我将乘以质数-指数对的所有可能组合。
例如,对于 180:
Given: prime factors of 180: [2, 3, 5]
Find maximum exponent of each factor:
180 / 2^1 = 90
180 / 2^2 = 45
180 / 2^3 = 22.5 - not an integer, so 2 is the maximum exponent of 2.
180 / 3^1 = 60
180 / 3^2 = 20
180 / 3^3 = 6.6 - not an integer, so 2 is the maximum exponent of 3.
180 / 5^1 = 36
180 / 5^2 = 7.2 - not an integer, so 1 is the maximum exponent of 5.
接下来,将这些组合进行到最大指数以获得因子:
2^0 * 3^0 * 5^0 = 1
2^1 * 3^0 * 5^0 = 2
2^2 * 3^0 * 5^0 = 4
2^0 * 3^1 * 5^0 = 3
2^1 * 3^1 * 5^0 = 6
2^2 * 3^1 * 5^0 = 12
2^0 * 3^2 * 5^0 = 9
2^1 * 3^2 * 5^0 = 18
2^2 * 3^2 * 5^0 = 36
2^0 * 3^0 * 5^1 = 5
2^1 * 3^0 * 5^1 = 10
2^2 * 3^0 * 5^1 = 20
2^0 * 3^1 * 5^1 = 15
2^1 * 3^1 * 5^1 = 30
2^2 * 3^1 * 5^1 = 60
2^0 * 3^2 * 5^1 = 45
2^1 * 3^2 * 5^1 = 90
2^2 * 3^2 * 5^1 = 180
所以因子列表 = [1, 2, 3, 4, 5, 6, 9, 10, 12, 15, 18, 20, 30, 36, 45, 60, 90, 180]
这是我到目前为止的代码。两个问题:首先,我认为它根本不是 Pythonic。我想解决这个问题。其次,我真的没有 Python 的方式来完成组合的第二步。出于羞耻,我让你免于荒谬的循环。
n 是我们想要分解的数字。 listOfAllPrimes 是一个预先计算的最多 1000 万个素数的列表。
def getListOfFactors(n, listOfAllPrimes):
maxFactor = int(math.sqrt(n)) + 1
eligiblePrimes = filter(lambda x: x <= maxFactor, listOfAllPrimes)
listOfBasePrimes = filter(lambda x: n % x ==0, eligiblePrimes)
listOfExponents = [] #(do I have to do this?)
for x in listOfBasePrimes:
y = 1
while (x**(y+1)) % n == 0:
y += 1
listOfExponents.append(y)
【问题讨论】:
-
您的代码错误。可能存在大于 n 的平方根的合格素数。例如,n = 7 或 n = 22。
-
@Sheldon L. Cooper 谢谢,绝对错了。我混淆了算法。
-
出于好奇,你解决的是哪个数字的问题?
标签: python algorithm factorization