简体   繁体   English

Python - 在不使用范围的情况下计算素数除数的数量

[英]Python - count the number of prime divisors without using range

I have to write a function that counts the total number of prime divisors of a given positive integer n.我必须编写一个函数来计算给定正整数 n 的素数除数的总数。 Since I have just started learning python a week ago, I am not allowed to use for loop with range.由于我一周前才开始学习python,因此不允许使用带有范围的for循环。 Below is what I have so far:以下是我到目前为止所拥有的:

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)

So I know that the exceeding maximum recursion depth error occurs at this line if n % i == 0 and num_of_divisors(i, 1) == 2 but I don't know how to check if the divisor is prime so that the function can work appropriately.所以我知道if n % i == 0 and num_of_divisors(i, 1) == 2会在这一行发生超过最大递归深度错误if n % i == 0 and num_of_divisors(i, 1) == 2但我不知道如何检查除数是否为素数,以便函数可以适当地工作。 Maybe I should write another helper function?也许我应该编写另一个辅助函数? Can someone help me with this?有人可以帮我弄这个吗? Any help is much appreciated :( Thank you!非常感谢任何帮助:(谢谢!

You can try this.你可以试试这个。

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)

output输出

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

Use this if want to store the count of prime factors and unique prime factors .如果要存储质因数和唯一质因数计数,请使用此选项。

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)

output输出

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.

if you are using Linux, this should work (no loops, no ranges, no nothing =):如果您使用的是 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]
>>> 

I hope you know how to take a length of the list using len()我希望你知道如何使用len()获取列表的长度

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM