歡迎辭

歡迎來到“篤志以礪,決起而飛”!
如果您是第一次來到本站,建議訪問本站導讀以便更快地了解本站。
如果您喜歡本站,歡迎訂閱

 

2012 年五月
« 四  
 123456
78910111213
14151617181920
21222324252627
28293031 

C++筆記:使用std::vector儲存質數表

本程序中最新使用的知識點:
1、常量整數 const int maxnum。
2、math.h 標準庫。
3、std::vector 和 std::vector::iterator 類型。

程序如下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/* 尋找所有的質數,並將尋找到的質數放入 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;
}

您也許喜歡

  1. C++筆記:習題 4.32-4.33
  2. C++筆記:迭代器
  3. C++筆記:習題4.28
  4. C++筆記:習題 4.34 – 4.35
  5. POJ 1328 Radar Installation 題解
  6. POJ 1308 Is It A Tree 題解

3 comments to C++筆記:使用std::vector儲存質數表

Leave a Reply

  

  

  

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>