csu 1030 素数槽

筛法求素数,难点在怎样减少内存,使用C++中的bool却是RE

/* 素数槽 C */
# include <stdio.h>
# include <string.h>

char a[1299710];    // 有点不伦不类。。。

void init(void)
{
int i, j;
memset(a, 0, sizeof(a));
for (i = 2; i < 1299710; ++i)
{
if (a[i]) continue;
j = 2*i;
while (j < 1299710)
{
a[j] = 1;
j += i;
}
}
}

int main()
{
int i, j, len, n;

init();
scanf("%d", &n);
while (n > 0)
{
scanf("%d", &i);
if (a[i])
{
j = i + 1;
len = 1;
while (a[i]){--i; ++len; }
while (a[j]){++j; ++len;}
printf("%d\n", len);
}
else printf("0\n");
--n;
}

return 0;
}
/* 素数槽 C++: Runtime Error*/
# include <iostream>
using namespace std;

bool a[1299710]; // 全局初始化为false

int main()
{
int i, j, len, n;
for (i = 2; i < 1299710; ++i)
{
if (a[i]) continue;
j = 2*i;
while (j < 1299710)
{
a[j] = true;
j += i;
}
}
cin >> n;
while (n > 0)
{
cin >> i;
if (a[i])
{
j = i + 1;
len = 1;
while (a[i]){--i; ++len;}
while (a[j]){++j; ++len;}
cout << len << endl;
}
else cout << 0 << endl;
--n;
}
return 0;
}

更优的做法参见—用位来代替bool:减小内存使用,提高运行速度

原文地址:https://www.cnblogs.com/JMDWQ/p/2364529.html