简体   繁体   中英

Simple Python Question about memory usage and for loops

I am currently taking an intro to cryptography course that is using python as the language in the class.

The problem we have is quite simple, and all it is asking us to do is figure out the smallest prime divisor for some integer n passed into the function, and will return said prime number.

The IDE we are using is telling me that the program keeps getting interrupted because I am running out of memory.

Below is my code:

    def smallest_prime_divisor(n):
        if(n%2==0):
            return 2;
        for i in range(3, n):
            if(n%i==0):
                if(is_prime(i)):
                    return i;
    return n;

    for n in range(1,120):
        x=2^n;
        x+=1;
        smallest_prime_divisor(x)

I don't believe the issue lies in the smallest_prime_divisor function, but somewhere in my second for loop, as I have tested quite a few numbers using just

    smallest_prime_divisor(x); #where x is equal to all integers 1-20

I know this seems like a simple question but it is driving me mad that I can't seem to find the right words to search google for the correct answer.

Your issue is likely with your is_prime() function that if I had to guess, is recursively calling itself. Here is an implementation of is_prime using Wilsom's theorem that will run without returning a memory error.

from math import factorial

def is_prime(n):
    return factorial(n - 1)  % n == n - 1

def smallest_prime_divisor(n):
    if(n%2==0):
        return 2
    for i in range(3, n):
        if(n%i==0):
            if(is_prime(i)):
                return i
    return n

for n in range(1,120):
    # Notice this line as well 'Paritosh Singh' mentioned in the comments why it is ** and not ^.
    x=2**n
    x+=1
    smallest_prime_divisor(x)

Notice the change between x=2^n and x=2**n as well.

You're using Python2, aren't you?

The problem is in this line of the smallest_prime_divisor() function:

    for i in range(3, n):

In Python2, range(x,y) generates a list of every number from x to y-1 . If yx is up in the billions, you're going to be eating up a lot of memory.

The solution is simple; replace range with xrange , which only generates the next number in the list when you ask for it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM