pythonrecursion

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. Since I have just started learning python a week ago, I am not allowed to use for loop with range. 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. Maybe I should write another helper function? Can someone help me with this? Any help is much appreciated :( Thank you!


Solution

  • 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.