斐波那契数列的3种求法及几种素数筛法

递推法

#include<stdio.h>
long long sum[40];//也可以不用开数组 
int main()
{
	int n;
	scanf("%d",&n);
	sum[1]=1;
	sum[2]=1;
	for(int t=3;t<=n;t++)
	{
		sum[t]=sum[t-1]+sum[t-2];
	}
	printf("%lld",sum[n]);
	return 0;
} 

递归法

#include<stdio.h>
long long F(int x)
{
	if(x==1||x==2)
	{
		return 1;
	}
	else
	{
		return F(x-1)+F(x-2);
	}
}
int main()
{
	int n;
	scanf("%d",&n);
	printf("%lld",F(n));
	return 0;
} 

矩阵快速幂法

#include<stdio.h>
#include<string.h>
#define MOD 1000000007
struct Mat
{
	long long  a[5][5];
};
Mat res,ans;
Mat Mul(Mat x,Mat y)
{
	Mat s;
	memset(s.a,0,sizeof(s.a));
	for(int t=0;t<2;t++)
	{
		for(int j=0;j<2;j++)
		{
			for(int k=0;k<2;k++)
			{
				s.a[t][j]+=x.a[t][k]*y.a[k][j];
				s.a[t][j]%=MOD;
			}
		}
	}
	return s;
}
void init()
{
	for(int t=0;t<2;t++)
	{
		for(int j=0;j<2;j++)
		{
			if(t==j)
			{
				ans.a[t][j]=1;
			}
			else
			{
				ans.a[t][j]=0;
			}
		}
	}
}
void Quick_pow(long long  n)
{
	init();
	while(n)
	{
		if(n&1)
		{
			ans=Mul(ans,res);
		}
		res=Mul(res,res);
		n>>=1;
	}
}

int main()
{

	long long n;
	while(scanf("%lld",&n)!=EOF)
	{
	res.a[0][0]=1;
	res.a[0][1]=1;
	res.a[1][0]=1;
	res.a[1][1]=0;
	Quick_pow(n-1);
	printf("%lld
",ans.a[0][0]);
    }
	return 0;
}

素数筛法

埃氏筛法:

#include<stdio.h>
#include<string.h>
#define maxn 100005
bool vis[maxn];
int Prime[maxn];
void Prime_E(int x){
	for(int t=2;t<=x;t++){
		if(vis[t]==true){
			for(int j=2*t;j<=x;j+=t){
				vis[j]=false;
			}
		}
	}
}
int main()
{
	int n;
	scanf("%d",&n);
	memset(vis,true,sizeof(vis));
	Prime_E(n);
	for(int t=2;t<=n;t++){
		if(vis[t]==true){
			printf("%d ",t);
		}
	}
	return 0;
}

欧拉筛法

#include<stdio.h>
#include<string.h>
#define maxn 100005
bool vis[maxn];
int prime[maxn];
void oula() {
	int cnt=0;
	memset(prime,0,sizeof(prime));
	memset(vis,false,sizeof(vis));
	for(int t=2; t<maxn; t++) {
		if(!vis[t])
			prime[cnt++]=t;
		for(int j=0; j<cnt&&t*prime[j]<maxn; j++) {
			vis[t*prime[j]]=true;
			if(t%prime[j]==0)
				break;
		}
	}
}
int main()
{
	int n;
	scanf("%d",&n);
	oula();
	for(int t=2;t<=n;t++){
		if(vis[t]==false){
			printf("%d ",t);
		}
	}
	return 0;
}


 

原文地址:https://www.cnblogs.com/Staceyacm/p/10781783.html