我正在研究一个项目欧拉问题,它需要整数的因式分解。我可以列出所有的素数,这些素数是一个给定数的因子。算术的基本定理意味着我可以用这个列表来推导
每一个
数字的系数。
我目前的计划是把基素数列表中的每一个数都取出来,并提高它的幂,直到它不再是一个整数因子来找到每个素数的最大指数。然后,我将把素数-指数对的每一个可能的组合相乘。
例如,对于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]
这是迄今为止我掌握的代码。有两个问题:第一,我觉得这根本不是什么蟒蛇。我想修一下。第二,我
真的?
没有一个蟒蛇的方法来做组合第二步。出于羞愧,我把你从这套荒谬的圈套中解救了出来。
n是我们要考虑的数字。所有素数的列表是一个预先计算的素数列表,最多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)