利用Eratosthenes筛法求解素数问题

#include"bitmap.h"

void Eratosthenes(int n)
{
	Bitmap B(n);
	B.set(0);
	B.set(1);//0&1都不是素数

	for (int i = 2; i < n; i++)
	{
		//反复地从下一个可以认定的素数i开始
		if (!B.test(i))
		{
			//注意for循环初始值以及素数判定条件的结合
			for (int j = __min(i, 46340) * __min(i, 46340); j < n; j += i)
			{
				B.set(j);//将下一个数标记为合数
			}
		}
	}
	//这里可以将素数输出,也可以将其导入到文件中
	//此处选择前者
	int j = 0;
	for (int i = 0; i < n; i++)
	{
		if (!B.test(i))
		{
			cout << i << "\t";
			j++;
		}
		if (j % 10 == 0)
		{
			cout << endl;
		}
	}
}

int main()
{
	//输出100以内所有的素数
	Eratosthenes(100);
	system("pause");
	return 0;
}
发布了17 篇原创文章 · 获赞 17 · 访问量 163

猜你喜欢

转载自blog.csdn.net/dosdiosas_/article/details/105487375