PROBLEM C: 孿生素數

Description

 這一日,快碼佳編四兄弟姐妹碰到了達數學家劉徽。是中國數學史上一個非常偉大的數學家,在世界數學史上,也佔有傑出的地位.他的傑作《九章算術注》和《海島算經》,是我國最寶貴的數學遺產。他們很快討論起素數來了。在素數的大家庭中,大小相差爲2的兩個素數稱之爲一對“孿生素數”,如3和5、17和19等。請你編程統計出不大於自然數n的素數中,孿生素數的對數。

Input

 多組測試數據,每組輸入一個整數n,1 <=n <= 10000

Output

 若干行,每行2個整數,之間用一個空格隔開,從小到大輸出每一對孿生素數

Sample Input

100

Sample Output

3 5
5 7
11 13
17 19
29 31
41 43
59 61
71 73

思路:模擬O(n*sqrt(n))能過

#include<iostream>
#include<vector>
#include<queue>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=1e5;
typedef long long LL;
LL a[maxn];//存素數 
int main(void)
{
	LL n;
	while(cin>>n)
	{
		if(n==0) continue;
		int cnt=1;
		for(LL i=1;i<=n+10;i++) a[i]=0;
		
		for(LL j=2;j<=n;j++)
		{
			int flag=1;
			for(LL i=2;i<=j/i&&flag;i++)
			{
				if(j%i==0)
				{
					flag=0;
					break;
				}
			}
			if(flag==1)
			{
				a[cnt++]=j;
			//	cout<<"a["<<cnt<<"]="<<a[cnt]<<endl;
			}
		}
	//	for(LL i=1;i<=cnt;i++)
	//		cout<<a[i]<<endl;
		for(LL i=1;i<=cnt;i++)
		{
			if(a[i+1]-a[i]==2)
			{
				cout<<a[i]<<" "<<a[i+1]<<endl;
			}
		}
	}

return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章