篩選法和預處理 以及HDOJ1215的優化

1. 篩選法求給定範圍內的質數。

一般求法(即:已經優化到了sqrt(N) :

#include<stdio.h>
#include<math.h>
int main()
{	int i,n,x;
	while(scanf("%d",&n)==1)
	{	x=(int)sqrt(n);
		for(i=2;i<=x;i++)
		     if(n%i==0)    break; 
		if(i>x)    printf("YES\n");
		else           printf("NO\n");
	}
}

2. 經過篩選和預處理的方法:


//需求:給定N(1< N <= 100000) 打印出小於N的所有質數。

#include <iostream>
#include <cstring>

using namespace std;

const int MAX = 100001;

int main()
{
	int N;
	int ans[MAX];

	memset(ans,0,sizeof(int)*MAX);
	ans[1] = 1;
	for(int i=2;i<=MAX;i++)
	{
		if(ans[i] == 0)//基本思想:就是將所以質數的i(i=1,2,..)的倍數都設置爲非質數。
			for(int j=i+i;j<=MAX;j+=i)//那麼經過篩選之後的就剩下的只有質數。
				ans[j] = 1;
	}
	while(cin>>N)
	{
		cout<<2;
		for(int i=3;i<=end;i++)
			if(ans[i] == 0)
				cout<<" "<<i;
		cout<<endl;
	}


	return 0;
}

3. 1215:

題目大意:求給定輸入一個整數N(1=<N<=50000)求出N的所以真因子之和,例如:

輸入:

8

10

20

輸出:

7

8

22

代碼如下:

//真因子之和。
//Time:93MS
//Mem :2252K


#include <iostream>
#include <cstring>
#include <stdio.h>

using namespace std;

int ans[500001];

int main()
{
	memset(ans, 0, 500001*sizeof(int));//memst是按字節設置的,所以只能設置爲0。
	for(int i=2;i<=250000;i++)
	{
		for(int j = 2; i*j < 500001; j++) 
			ans[i*j] += i;	
	}
	int t;
	scanf("%d",&t);
	int n;
	while(t--)
	{
		scanf("%d",&n);
		printf("%d\n",ans[n]+1); //一定要用printf,效率真心差很多。
	}


	return 0;
}






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