Shreyash Waghmare
Shreyash Waghmare

Reputation: 1

Finding largest prime factor for a number with python

def prime(x):
    for a in range(2, x):
        if x%a == 0:
            break
    else:
        return x
num = 0 
largest = 0
for i in range(2, 600851475143):
    if 600851475143%i == 0:
        num = prime(i)
    
    if largest < num:
        largest = num
print(largest)

I got the answer but it's not running successfully I'm getting this error : '<' not supported between instances of 'int' and 'NoneType' Can you please tell me what's wrong with the code? I can't figure it out.

Upvotes: 0

Views: 43

Answers (3)

Moritz Ortwein
Moritz Ortwein

Reputation: 19

def prime(x) calls break when if x%a == 0: is true, but can't return anything.

To solve this issue use:

def prime(x):
    for a in range(2, x):
        if x%a == 0:
            break
    return x
    

By the way: Finding Primefactors is more an recursive Problem than an interative.

Upvotes: 0

Nate
Nate

Reputation: 1

prime does return None, if it stops with break.

Instead of break, you could use return 0. This won´t run into the same error and will not change largest, since largest>=0.

But I guess this is a very inefficient way to get the largest primefactor. It would probably be faster to factorize and then to look for the greatest factor.

Upvotes: 0

Scott Hunter
Scott Hunter

Reputation: 49848

When prime is called with a non-prime, it never executes a return statement, and thus returns None.

Upvotes: 1

Related Questions