Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用n+的目的是什么;1在这个eratosthenes函数中?_Python_Sieve Of Eratosthenes - Fatal编程技术网

Python 使用n+的目的是什么;1在这个eratosthenes函数中?

Python 使用n+的目的是什么;1在这个eratosthenes函数中?,python,sieve-of-eratosthenes,Python,Sieve Of Eratosthenes,这里是一个简单的素数埃拉托斯提尼筛,它删除了倍数,并将它们附加到倍数的空列表中。我的问题是,如果我在两个for循环中都使用n而不是n+1,那么答案是一样的 def eratosthenes(n): multiples = [] for i in xrange(2, n+1): if i not in multiples: print i for j in xrange(i*i, n+1, i):

这里是一个简单的素数埃拉托斯提尼筛,它删除了倍数,并将它们附加到倍数的空列表中。我的问题是,如果我在两个
for
循环中都使用
n
而不是
n+1
,那么答案是一样的

def eratosthenes(n):
    multiples = []
    for i in xrange(2, n+1):
        if i not in multiples:
            print i
            for j in xrange(i*i, n+1, i):
                multiples.append(j)
返回类似的输出

eratosthenes(10)
2
3
5
7
如果在两个循环中用
n
替换
n+1
,则输出仍然相同:

def eratosthenes(n):
    multiples = []
    for i in xrange(2, n):
        if i not in multiples:
            print i
            for j in xrange(i*i, n, i):
                multiples.append(j)
返回与上述函数相同的输出

eratosthenes(10)
2
3
5
7
我的问题是为什么我们使用
n+1
而不是
n

Python
range()
xrange()
函数,如Python切片表示法,不包括结束值
xrange(2,10)
生成8个从
2
9
10的数字
n+1
确保
n
是生成范围的一部分

使用
eratosthenes(7)
eratosthenes(11)
查看差异;10不是质数,正在被过滤掉。

尝试
eratosthenes(11)
并比较差异。