要使用Sieve of Eratosthenes算法生成素数列表,在Java中,我可以这样做:
public static void processSieve(boolean[] sieve)
{
for (int i = 2; i < sieve.length; i++)
sieve[i] = true;
for (int i = 2; i < Math.sqrt(sieve.length); i++)
{
if (sieve[i] == true)
{
for (int j = i * 2; j < sieve.length; j += i)
sieve[j] = false;
}
}
}
但是,Python没有C-Style for循环,所以我不得不使用while循环来完成同样的事情:
def processSieve(sieve):
sieve = [True for i in range(HOWMANY + 1)]
sieve[0], sieve[1], i, j = False, False, 2, 0
while i <= math.sqrt(len(sieve)):
if sieve[i] == True:
j = i * 2
while j < len(sieve):
sieve[j] = False
j += i
i += 1
是否可以在Python中使用for..in循环来模拟上面写的Java for循环?或者我被迫只使用while循环?
答案 0 :(得分:1)
您可以使用for循环:
>>> for i in range(2,10,3):
... print i
...
2
5
8
范围(...) 范围([start,] stop [,step]) - &gt;整数列表
Return a list containing an arithmetic progression of integers. range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0. When step is given, it specifies the increment (or decrement). For example, range(4) returns [0, 1, 2, 3]. The end point is omitted! These are exactly the valid indices for a list of 4 elements.
所以
for (int j = i * 2; j < sieve.length; j += i)
可以&#34;翻译&#34;到:
for j in range(i*2, len(sieve), i):
答案 1 :(得分:1)
1.Python有一个for in
循环,它经常与range()
2.由于math.sqrt
生成浮点数,您应该使用int()
来获取整数
3.没有必要在python
中初始化i
def processSieve(sieve):
sieve = [True for i in range(HOWMANY + 1)]
sieve[0], sieve[1], j = False, False, 0
for i in range(2, int(math.sqrt(len(sieve))):
if sieve[i] == True:
j = i * 2
while j < len(sieve):
sieve[j] = False
j += i
i += 1