Prime Distance

筛法||暴力

这道题是可以用筛法,先筛出2-sqrt(N)内的质数,然后让这些质数去筛掉L-R内的合数,就行;

但我们显然不能向正解屈♂服

我们用判断大质数的利器:M-R算法,高效的判断一个数是否是质数,复杂度(R-L+1)*log(R-L+1);

code:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<ctime>
using namespace std;
#define int long long 
#define I_love signed
#define zmd main()
int l,r;
inline int abs_(int x,int y)
{
	return x>y?x-y:y-x;
}
inline int fast_pow(int a,int b,int p)
{
	int ans=1;
	while (b)
	{
		if (b&1) ans=ans*a%p;
		a=a*a%p;
		b>>=1;
	}
	return ans;
}
inline bool mr(int k)
{
	if (k==1) return 0;
	if (k==2) return 1;
	for (int i=1;i<=40;++i)
	{
		int tmp=rand();
		tmp=tmp*100000%(k-2)+2;
		if (fast_pow(tmp,k-1,k)!=1) return 0;
	}
	return 1;
}
I_love zmd
{
	srand(time(NULL));
	while (scanf("%lld%lld",&l,&r)!=EOF)
	{
		int last =0;
		int minn=1e17,mx=-1e17,num1a=-1,num1b=-1,num2a=-1,num2b=-1;
		for (int i=l;i<=r;++i)
		{
			if (mr(i))
			{
				if (!last) last=i;
				else 
				{
					if (minn>abs_(i,last))
					{
						minn=abs_(i,last);
						num1a=last,num1b=i;
					}
					if (mx<abs_(i,last))
					{
						mx=abs_(i,last);
						num2a=last,num2b=i;
					}
					last=i;
				}
			}
		}
		if (num1a==-1) printf("There are no adjacent primes.\n"); 
		else printf("%lld,%lld are closest, %lld,%lld are most distant.\n",num1a,num1b,num2a,num2b);
	}
}

收获:

关于质数的问题可以用M-R算法考虑一下,简化思维,代码量!!

posted @ 2018-09-26 15:51  Splitor  阅读(409)  评论(0编辑  收藏  举报