Skip to content
Advertisement

Trying to find the largest prime factor but I don’t know what is wrong. Please give me advice [closed]

I don’t know what is wrong. I am trying to find largest prime factor

import math
def getfactor(num):
    factors = []
    for i in range(2,int((math.sqrt(num)))+1):
        if num % i == 0:
            factors.append(i)

    return factors

def determineprime(num):
    factor = []
    for i in range(2,num + 1):
        if num % i == 0:
            factor.append(i)
    if len(factor) == 1:
        return True
    else:
        return False

factors = getfactor(600851475143)
primes = []
print(factors)
for i in factors:
    determineprime(i)
    if i:
        primes.append(i)
print(primes[-1])

Advertisement

Answer

Change:

    determineprime(i)
    if i:
        primes.append(i)

to:

    if determineprime(i):
        primes.append(i)

The original version was calling determineprime(i), discarding the result, and always appending i to primes. The corrected version will only append i to primes if determineprime(i) returns true.

Update: As Mark Tolonen pointed out, getfactor will return an empty list if its argument is prime. In that case, the number itself should be returned as the sole element of the list. It can just check to see if the list is empty before returning, and if so, append the number itself, since it must be prime in that case.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement