[英]Finding prime_factors that returns the prime factors of an integer as a list
def prime_factors(n):
i = 2
lst = []
while i <= n:
if isprime(i):
lst.append(i)
i += 1
return lst
def isprime(n):
n = isdivisor(n)
i = 2
lst = []
for j in n:
while i <= j/2:
if j % i != 0:
return True
else:
return False
i += 1
def isdivisor(n):
i = 2
lst = []
while i <= n/2:
if n % i == 0:
lst.append(i)
i += 1
return lst
print prime_factors(15)
First, I tried to find divisors of integer n
and checked the divisors whether they are prime or not.However the output is somehow [10, 14, 15]
instead of [3,5]
.首先,我试图找到整数
n
的除数并检查除数是否为素数。然而,输出不知何故是[10, 14, 15]
而不是[3,5]
。 Is it because I can't do the assignment n = isdivisor(n)
or something else ?是因为我不能做任务
n = isdivisor(n)
还是别的什么?
I just wrote a pice of code to do It, without using libs.我只是写了一段代码来做它,没有使用库。 I hope It can help you.
我希望它可以帮助你。
my code:我的代码:
def get_square_root(n):
"""Return square root of n."""
return n ** (1.0 / 2)
def is_divisor(n, d):
"""Return True if n divides d, False otherwise."""
return n % d == 0
def is_prime(n):
"""Return True if n is prime, False otherwise."""
limit = int(get_square_root(n))
for i in range(2, limit+1):
if is_divisor(n, i):
return False
return True
def get_prime_factors(n):
"""Return a list of the prime factors of n."""
prime_factors = []
for i in range(2, n):
if is_divisor(n, i) and is_prime(i):
prime_factors.append(i)
return prime_factors
if __name__ == '__main__':
n = 15 # Change n to test
prime_factors = get_prime_factors(n)
print(prime_factors)
output:输出:
[3, 5]
There are some logical errors in your code.您的代码中有一些逻辑错误。 You are overcomplicating things somewhat by returning lists of divisors and primes.
您通过返回除数和质数列表使事情变得过于复杂。 You already have a loop in the
prime_factors()
to go through all the numbers from 2 to n
.您已经在
prime_factors()
有一个循环来遍历从 2 到n
所有数字。 So you can simplify your isdivisor()
and isprime()
functions:所以你可以简化你的
isdivisor()
和isprime()
函数:
def isdivisor(i, n):
return n % i == 0
def isprime(n):
i = 2
while i < n:
if n % i == 0:
return False
i += 1
return True
Then change your main loop in prime_factors()
like this:然后像这样更改
prime_factors()
主循环:
def prime_factors(n):
i = 2
lst = []
while i < n:
if isdivisor(i, n) and isprime(i):
lst.append(i)
i += 1
return lst
Output:输出:
>>>prime_factors(15)
[3,5]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.