![](/img/trans.png)
[英]Printing the sum of prime divisors of each number in a given range in python
[英]Python - count the number of prime divisors without using range
我必須編寫一個函數來計算給定正整數 n 的素數除數的總數。 由於我一周前才開始學習python,因此不允許使用帶有范圍的for循環。 以下是我到目前為止所擁有的:
def count_prime_divisors(n):
return num_of_divisors(n, 1)
def num_of_divisors(n, i):
if i > n:
return 0
if n % i == 0 and num_of_divisors(i, 1) == 2:
return 1 + num_of_divisors(n, i+1)
else:
return num_of_divisors(n, i+1)
所以我知道if n % i == 0 and num_of_divisors(i, 1) == 2
會在這一行發生超過最大遞歸深度錯誤if n % i == 0 and num_of_divisors(i, 1) == 2
但我不知道如何檢查除數是否為素數,以便函數可以適當地工作。 也許我應該編寫另一個輔助函數? 有人可以幫我弄這個嗎? 非常感謝任何幫助:(謝謝!
你可以試試這個。
def prime_fac(n,count=0,prime_num=2):
if n==1:
print('Number of prime factors',count)
return
elif n%prime_num==0:
print(prime_num)
return prime_fac(n//prime_num,count+1,prime_num)
else:
return prime_fac(n,count,prime_num+1)
prime_fac(100)
prime_fac(12)
prime_fac(999)
輸出
2
2
5
5
Number of prime factors 4
2
2
3
Number of prime factors 3
3
3
3
37
Number of prime factors 4
如果要存儲質因數和唯一質因數的計數,請使用此選項。
def prime_fac(n,count=0,prime_num=2,prime_set=set()):
if n==1:
print('Number of prime factors',count)
return count,prime_set
elif n%prime_num==0:
print(prime_num)
prime_set=prime_set|{prime_num} #set union operation
return prime_fac(n//prime_num,count+1,prime_num,prime_set)
else:
return prime_fac(n,count,prime_num+1,prime_set)
a=prime_fac(100)
print(a)
輸出
2
2
5
5
Number of prime factors 4
(4, {2, 5}) #a looks like this where 4 is prime factors count and {2,5} is unique prime factors.
如果您使用的是 Linux,這應該可以工作(沒有循環,沒有范圍,沒有什么 =):
>>> import os
>>>
>>> def factor(num) :
... output = os.popen( 'factor %d' % num ).read()
... return map( int, output.split(':')[-1].split())
...
>>> print factor(128)
[2, 2, 2, 2, 2, 2, 2]
>>>
我希望你知道如何使用len()
獲取列表的長度
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.