我是C++的新手,我正试图解决初学者的问题,即在0-n个数之间找到所有素数。我在网上看到了这段代码,它运行得很好。
然而,我的问题是,在“bool primen +1;”语句中,'+ 1‘的用法是什么?我已经把它从代码中删除了,一切看起来都很好。这是必要的还是多余的?
void SieveOfEratosthenes(int n) {
bool prime[n + 1];
memset(prime, true, sizeof (prime));
for (int p = 2; p * p <= n; p++) {
// If prime[p] is not changed, then it is a prime
if (prime[p] == true) {
// Update all multiples of p
for (int i = p * 2; i <= n; i += p)
prime[i] = false;
}
}
// Print all prime numbers
for (int p = 2; p <= n; p++)
if (prime[p])
cout << p << endl;
}
int main() {
int n = 1000;
cout << "Following are the prime numbers smaller "
<< " than or equal to " << n << endl;
SieveOfEratosthenes(n);
return 0;
}发布于 2016-01-20 09:03:51
在C++中,大小为N的数组具有从0到N-1的索引。因此,针对您的问题,对于N索引分配N+1大小数组。所以定义了N数的素数。
发布于 2016-01-20 09:55:00
在C++ (和许多其他语言)中,大小为n的数组有一个0到(n - 1)的索引。在这种情况下,您需要检查每个数字,直到包含n。因此,在索引prime[n]处,需要在数组中为n设置一个点。只有当您将数组的大小过大1时,此索引才会存在。否则,数组将在prime[n - 1]处停止。
即使去掉- 1,它也能工作,原因是C++对数组边界并不挑剔--一旦您拥有一个数组,您就可以合法地读取或写入任何索引,无论该索引是否安全。注意,我说的是法律上的,而不是安全的--这可能是非常危险的行为。
https://stackoverflow.com/questions/34894483
复制相似问题