I have a Python Code to get the largest prime factor of a Number and the below is my code When I give the input to the number up to an 8-digit number takes a few minutes but when I tried running the code for a 12-digit number 600851475143 it took more time and still it didn't give any output or any error. So is there any way how to get the output for the 12-digit numbers quickly?
def large_prime_fact(num):
prime_factors=[]
if num==2 or num==3:
return(prime_factors.append(num))
if num%2==0:
prime_factors.append(2)
for i in range(3,num,2):
cnt=0
if num%i==0:
for j in range(2,i):
if i%j==0:
cnt+=1
if cnt==0 and i!=2:
prime_factors.append(i)
return prime_factors
if __name__=='__main__':
number=int(input('Enter the number:'))
print('The Largest prime factor for',number,'is :',max(large_prime_fact(number)))
As Karl Knechtel pointed out your approach is seriously flawed. Here on SO there are lots of questions about prime numbers and factorization, which you may want to read.
That said, here's my solution. It may still benefit from further optimizations, but it solves your 600851475143 example in about 1ms.