简体   繁体   English

关于内存使用和 for 循环的简单 Python 问题

[英]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.我目前正在学习使用 python 作为课堂语言的密码学课程。

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.我们遇到的问题很简单,它要求我们做的就是找出传递给函数的某个整数 n 的最小素数除数,并返回该素数。

The IDE we are using is telling me that the program keeps getting interrupted because I am running out of memory.我们正在使用的 IDE 告诉我程序不断被中断,因为我的内存不足。

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 函数中,而是在我的第二个for 循环中的某个地方,因为我已经使用只测试了很多数字

    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.您的问题可能与您的is_prime()函数有关,如果我不得不猜测,它会递归地调用自己。 Here is an implementation of is_prime using Wilsom's theorem that will run without returning a memory error.下面是使用Wilsom 定理is_prime实现,它可以在不返回内存错误的情况下运行。

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.请注意x=2^nx=2**n之间的变化。

You're using Python2, aren't you?您正在使用 Python2,对吗?

The problem is in this line of the smallest_prime_divisor() function:问题出在smallest_prime_divisor()函数的这一行:

    for i in range(3, n):

In Python2, range(x,y) generates a list of every number from x to y-1 .在 Python2 中, range(x,y)生成从xy-1的每个数字的列表。 If yx is up in the billions, you're going to be eating up a lot of memory.如果yx达到数十亿,您将占用大量内存。

The solution is simple;解决方法很简单; replace range with xrange , which only generates the next number in the list when you ask for it.xrange替换range ,它只会在您要求时生成列表中的下一个数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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