C++筆記:使用std::vector儲存質數表
本程序中最新使用的知識點:
- 常量整數 const int maxnum。
- math.h標準庫。
- std::vector和- std::vector::iterator類型。
程序如下。
/* 尋找所有的質數,並將尋找到的質數放入 vector 中進行窮舉。
 * By Ceeji
 */
const int maxnum = 10000;
 
#include <iostream>
#include <vector>
#include <math.h>
 
using namespace std;
 
typedef vector<int> intarr;
 
int main()
{
	intarr p = intarr();
	bool iszs;
	int max;
	for (int i = 1; i != maxnum; ++i) // 從 1 開始尋找質數。
	{
		if (i == 1)
		{
			iszs = false;
		}
		else
		{
			if (i == 2)
			{
				iszs = true;
			}
			else
			{
				max = (int)floor(sqrt((double)i));
				iszs = true;
				for (int j = 2; j != max + 1; ++j)
				{
					if (i % j == 0)
					{
						// 不是質數。
						iszs = false;
						break;
					}
				}
			}
			if (iszs)
			{
				p.push_back (i);
			}
		}
	}
	intarr::iterator iter = p.begin ();
	// 輸出
	while (iter != p.end ())
	{
		cout << *(iter++) << endl;
	}
	return 0;
}
© 轉載需附帶本文連結,依 CC BY-NC-SA 4.0 釋出。