-2

I'm trying to produce the sum of all prime factors of a number without using loop. However if the result of prime_factor(m, k) bigger than 2, when go to main(n) after factor=prime_factor(m, k), factor will be None

def prime_factor(m, k):
    if m%k==0:
        return k 
    else:
        prime_factor(m, k+1)

def main(n):
    if n<2:
        return 0
    if n==2:
        return n
    else:
        factor=prime_factor(n, 2)
        return factor+main(n//factor)
smci
  • 32,567
  • 20
  • 113
  • 146
T.J
  • 1
  • 1

1 Answers1

0

Your prime_factor function is not doing anything with the result of the recursive call. You need to return it:

def prime_factor(m, k):
    if m%k==0:
        return k 
    else:
        return prime_factor(m, k+1)         # need the return here

Also minor optimization but you could adjust your values so you start at 3 and do prime_factor(m, k+2) in the recursive call instead of k+1.

gowrath
  • 3,136
  • 2
  • 17
  • 32