hdu 1262 尋找素數對(素數的判斷,快速篩選素數)



尋找素數對
Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u


Description

哥德巴赫猜想大家都知道一點吧.我們現在不是想證明這個結論,而是想在程序語言內部能夠表示的數集中,任意取出一個偶數,來尋找兩個素數,使得其和等於該偶數. 
做好了這件實事,就能說明這個猜想是成立的. 
由於可以有不同的素數對來表示同一個偶數,所以專門要求所尋找的素數對是兩個值最相近的. 
 

Input

輸入中是一些偶整數M(5<M<=10000). 
 

Output

對於每個偶數,輸出兩個彼此最接近的素數,其和等於該偶數. 
 

Sample Input

20 30 40
 

Sample Output

7 13 13 17 17 23
 


素數的操作,要想不超時,那就要打表,既然打表,就用比較快的打表方式,素數快速打表


打好表以後,就從中間開始往前遍歷,找到合數的就輸出,然後跳出循環



附上代碼:

#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;


const int MAXN=10010;
bool notprime[MAXN];//值爲false表示素數,值爲true表示非素數 
void init() 
{
    memset(notprime,false,sizeof(notprime));
	notprime[0]=notprime[1]=true;
	for(int i=2;i<MAXN;i++){
		if(!notprime[i])
		{
			if(i>MAXN/i)
			continue;
			for(int j=i*i;j<MAXN;j+=i)     // i 爲素數,i 的倍數都不是 素數
			notprime[j]=true;
		}
	}
}

int main()
{
	init();
	int n;
	while(~scanf("%d",&n))
	{
		for(int i = n / 2;i >= 1;i--)
		{
			if(!notprime[i] && !notprime[n - i])   
			{
				printf("%d %d\n",i,n - i);
				break;
			}
		}
	}
	return 0;
}


發佈了106 篇原創文章 · 獲贊 31 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章