C++实现找100(任意)以内的质数--非常好的算法

很惊叹!

#include<iostream>
#include<bitset>
#include<cmath>

using namespace std;

int main()
{
     
	

	const int Max_number =10000    ;
	const int Test_number = static_cast<int>(sqrt(static_cast<double>(Max_number)));
	bitset<Max_number+1> numbers; //101个0


	numbers.set();   //10
	
	//0和1 忽略掉
	numbers[0]=0;
	numbers[1] = 0;
	for (int i = 1; i != Test_number + 1; i++)  //这里可以从2开始循环,不过前面numbers[1]已经是0了,下面的if语句很快就排除了,开始从2循环
	{
     
		if (numbers[i])
		{
     
			for (int j = 2 * i; j <=Max_number ; j += i)     //筛选倍数
				numbers.reset(j);
				//numbers[j] = 0;		
		}
		
	}

	cout << endl << Max_number  << "(包括) 以内的质数共有 " << numbers.count() << "个:\n\n";

	//输出所有的质数
	int account = 0;
	for (int i = 1; i <= Max_number; ++i)
	{
     
		if (numbers[i])
		{
     
			
			cout << i << " ";
			account++;              //为了更容易观看,每10个数字换行
			if (account % 10 == 0)
				cout << endl;
		}
	}

	
}

你可能感兴趣的:(杂谈)