0

I am trying to run the following code in sublime text:

def max_prime_factor(num):
    divisibles=[]
    prime_facors=[]
    for i in range(1,num):
        if num%i==0:
            divisibles.append(i)
        else:
            continue
    for j in divisibles:
        for k in range(2,j):
            if j%k==0:
                break
            else:
                continue

        prime_facors.append(j)
    return(max(prime_facors))

print(max_prime_factor(600851475143))

using a machine equipped with:

enter image description here

and getting the following error in the sublime text. Do I have to modify the code, because it is overwhelming? Tnx in advance!

enter image description here

OdatNurd
  • 21,371
  • 3
  • 50
  • 68
Max
  • 509
  • 1
  • 7
  • 21
  • 1
    This looks a lot like you're on Python 2. Use Python 3. – user2357112 May 28 '20 at 21:35
  • 1
    How did you notice that? – Max May 28 '20 at 21:41
  • 1
    Python 2 builds a list up front for `range`, and that list isn't going to fit in memory. That particular issue can usually be fixed by switching to `xrange`, but there are a lot of other reasons to prefer Python 3 over Python 2. – user2357112 May 28 '20 at 21:44
  • could using so many "for loops" be a reason for a very high computation? – Max May 28 '20 at 21:46
  • 1
    I removed your `sublimetext3` tag because errors in Python don't really have anything to do with the thing that executed the code (in this case Sublime executing `python` on your behalf). However if you were intending to use Python 3, then this is tangentially a Sublime issue (in that the default Build system for Sublime executes `python`, which might not be the version you expect, so you need to create one that executes the proper version of Python). – OdatNurd May 28 '20 at 21:48
  • I solved it by changing my build system following this medium: https://medium.com/@hariyanto.tan95/set-up-sublime-text-3-to-use-python-3-c845b742c720 – Max May 28 '20 at 22:02
  • 1
    They chose too big or a number, and that is why it is so computationally difficult. There is an algorithm called the sieve of eratosthenes that will solve the problem faster, but I don't know how they expect you to know that. One thing you can do is you can change `for i in range(1,num):` to `for i in range(2,math.ceil(math.sqrt(num))):` since you're never going to have a factor bigger than the square root. Also, before you start trying to solve for 600851475143, make sure you get 13195 working. Your solution isn't correctly detecting which factors (or divisibles as you called them) are prime. – hostingutilities.com May 28 '20 at 22:16

1 Answers1

1

From the comments it sounds like you're using Python 2. In that case you will need to use xrange instead or range. xrange works the same as range, but it is more memory efficent. See What is the difference between range and xrange functions in Python 2.X?

hostingutilities.com
  • 8,894
  • 3
  • 41
  • 51