0

While I was trying to find the largest prime factor of a number using the code below attached , I encountered OverflowError: Python int too large to covert to C long

def prime_factors(n):
    i = 2
    if prime(n)==1:
        return n
    while n>0 and i<n:
        if n % i ==0:
            n = n/i
            div = i
            prime_factors(n)
        else:
            i+=1

return div

def prime(n):
    for i in xrange(2,n):
        if n%i ==0:
            return 0
    return 1

num = int(raw_input())
print prime_factors(num)

Can anyone please help find a solution to this ?

P.S: I am a beginner in Python.

Kshitij Saraogi
  • 6,821
  • 8
  • 41
  • 71

1 Answers1

1

range() creates a list in memory, which will raise an error if n is too large. You should use xrange() instead, which will create a lazy-evaluated generator object.

DeepSpace
  • 78,697
  • 11
  • 109
  • 154