1

I have a (perhaps clumsy) function to find the largest prime factor of a number n (below).

def largest_prime_factor(n,factor=2):
    if n % factor == 0:
        if n == factor:
            return factor
        else:
            largest_prime_factor(n/factor,factor)
    else:
        largest_prime_factor(n,factor+1)

#Printing function output
print largest_prime_factor(600)

But when I try to print the function's returned output it simply says None. However, when I make the function print its output (below) it prints the correct answer (5). What am I doing wrong in the snippet above?

def largest_prime_factor(n,factor=2):
    if n % factor == 0:
        if n == factor:
            print factor #Printing, not returning
        else:
            largest_prime_factor(n/factor,factor)
    else:
        largest_prime_factor(n,factor+1)

#Calling the function
largest_prime_factor(600)
2
  • 3
    Hint: since you're using recursion - the print statement will only see the outer most return... Commented Oct 18, 2013 at 7:37
  • 1
    @JonClements do you ever sleep? Commented Oct 18, 2013 at 7:39

1 Answer 1

2

You missed some return calls :

def largest_prime_factor(n,factor=2):
    if n % factor == 0:
        if n == factor:
            return factor
        else:
            return largest_prime_factor(n/factor,factor)
    else:
        return largest_prime_factor(n,factor+1)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.