我正试图写一个程序来找到n!的素数因式分解。我以前已经成功地做到了,但是我找不到我已经写过的代码,所以我不得不重写它!:p代码如下: 在
import math
import numpy as np
import itertools as it
import operator as op
def primes(n):
"""A simple sieve to find the primes less than n"""
nums = np.arange(3,n+1,2)
sqrtn = int(n**0.5)/2
for step in nums[:sqrtn]:
if step:
nums[step*step/2-1::step]=0
return [2] + map(int, filter(None, nums))
def factFactors(n):
"""Finds the prime factorization of n! using the property found
here: http://en.wikipedia.org/wiki/Factorial#Number_theory"""
ps = primes(n)
for p in ps:
e = 0
for i in it.count(1):
epeice = n/(p**i)
if epeice == 0: break
e += epeice
yield p, e
if __name__=="__main__":
x = list(factFactors(100))
print x, reduce(op.mul, [p**e for p, e in x], 1)==math.factorial(100)
输出如下:
^{pr2}$我已经看了好几个小时了,我不知道怎么了。。。在
这段代码在我做实验的时候改变了很多次,但是当前版本的一个问题是由于
factFactors
是一个生成器调用
list
将耗尽生成器,因此reduce
没有任何操作。请改用x = list(factFactors(100))
。在-
在更正了
^{pr2}$result
/results
的错误之后(好吧,就是我开始写这篇文章时就有的!)我无法运行代码:但它确实暗示了问题可能出在哪里。(由于代码不会为我运行,我不能确定,但我有理由确定。)
primes
返回的大多数元素不是Python任意精度整数,而是有限范围的numpy整数:对它们的操作可能会溢出。如果我将
p
和e
转换为int
:我明白了
如果您想方便地使用
numpy
数组索引,可以使用object
的数据类型,即但老实说,我建议您不要在这里使用
numpy
。在相关问题 更多 >
编程相关推荐