筛选法求100以内的素数:
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
int i, j;
int not_prime[100] = {0}; //initial array not_prime[10] to all zero(0);
printf("Prime number in 100 are as follows:/n");
for ( i = 2; i < 100; i++) // loop from 2 to 100
{
if ( !not_prime[i] ) // judge whether the ith number is a prime number or not
{
printf("%4d is a prime number./n", i);
for (j = i * i; j < 100; j += i) //if the ith number is a prime number, then the multiples of it is composite number.
not_prime[j] = 1;
}
}
return 0;
}
本文介绍了一个简单的筛选法程序,用于找出100以内的所有素数。该程序采用C++语言实现,并利用一个标记数组来判断每个数是否为素数。对于每个找到的素数,其倍数都会被标记为合数。
1195

被折叠的 条评论
为什么被折叠?



