我正在进行pyschools练习,我在主题5问题12 - Prime Factorization中遇到问题,我必须这样做:
给定一个正整数,写一个函数来计算可以多次一起运算的素数因子,以获得相同的整数。
Examples
>>> primeFactorization(60)
[2, 2, 3, 5]
>>> primeFactorization(1050)
[2, 3, 5, 5, 7]
>>> primeFactorization(1)
[]
这是我的代码:
import operator
import functools as fun
def primeFactorization(num):
num = num
primes = []
result = []
if num > 1:
[primes.append(x) for x in range(2, num) if all(x % y != 0 for y in range(2, x))]
multy = fun.reduce(operator.mul, result, 1)
for number in primes:
if num % number == 0 and multy != num:
result.append(number)
return result
这让我回答:
Test Cases Expected Result Returned Result
primeFactorization(33) [3, 11] [3, 11]
primeFactorization(84) [2, 2, 3, 7] [2, 3, 7]
primeFactorization(1) [] []
我试过这个并且我的私人测试用例失败了:
import operator
import functools as fun
def primeFactorization(num):
num = num
primes = []
result = []
if num > 1:
[primes.append(x) for x in range(2, num) if all(x % y != 0 for y in range(2, x))]
multy = fun.reduce(operator.mul, result, 1)
for number in primes:
if num % number == 0:
result.append(number)
multy = fun.reduce(operator.mul, result, 1)
y = num/multy
if y != 1 and y in primes:
result.insert(0, int(y))
return result
Test Cases Expected Result Returned Result
primeFactorization(33) [3, 11] [3, 11]
primeFactorization(84) [2, 2, 3, 7] [2, 2, 3, 7]
Private Test Cases Passed Failed
primeFactorization(1) [] []
我能做些什么来传递?
答案 0 :(得分:2)
为什么要这么复杂?
找到给定数字X
的所有素因子的问题与找到我们可以将X
分成的最小数字(大于1)的集合相同。
要解决此问题,我们可以从查找除n
的最小数字X
开始。
这是X
的第一个主要因素。然后我们可以通过找到X/n
def primeFactorization(X):
possible = [2] + range(3,int(ceil(sqrt(X)))+1,2)
for p in possible:
if X % p == 0:
return [p] + primeFactorization(X/p)
return [X]
primeFactorization(3*3*7*5*11*13*31)
> [3,3,5,7,11,13,31]