计蒜客--T1808--质数和

给定 22 个整数 a,ba,b 求出它们之间(包括 a,ba,b)的所有质数的和。

输入格式

两个整数 a,b\ (1\le a,b\le 10^5)a,b (1≤a,b≤105)。

输出格式

一个整数,表示范围内的质数和。

输出时每行末尾的多余空格,不影响答案正确性

样例输入
999 10
样例输出
76110

思路一:暴力判断+统计即可;---数据范围小,更适合;<50ms

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long LL;
bool prime(LL n){
	if(n==2)	return true;
	if(n==1)	return false;
	for(int i=2;i<=sqrt(n);i++)
		if(n%i==0)	return false;
	return  true;
}
int main(){
    LL a,b,ans=0;
    scanf("%lld%lld",&a,&b);
    if(a>=b)	swap(a,b);
    for(LL i=a;i<=b;i++)
    	if(prime(i))
    		ans+=i;
    printf("%lld\n",ans);
    return 0;
}

思路二:Miller_Rabin算法;数据范围更大适合,此题时间<500ms

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long LL;
LL mul_mod(LL a,LL b,LL mod){
    LL ret=0;
    while(b){
        if(b&1)    ret=ret+a;
        if(ret>=mod)	ret-=mod;
        a=a+a;
        if(a>=mod)	a-=mod;
        b>>=1;
    }
    return ret;
}
LL pow_mod(LL a,LL b,LL mod){
    LL ret=1;
    while(b){
        if(b&1)ret=mul_mod(ret,a,mod);
        a=mul_mod(a,a,mod);
        b>>=1;
    }
    return ret;
}
bool Miller_Rabin(LL n){//判断素数 
    LL u=n-1,pre,x;
    int i,j,k=0;
    if(n==2||n==3||n==5||n==7||n==11)	return true;
    if(n==1||(!(n%2))||(!(n%3))||(!(n%5))||(!(n%7))||(!(n%11))) return
            false;//初始化判断素数 
    for(;!(u&1);k++,u>>=1);//按照要求转换形式 
    for(i=0;i<10;i++){
        x=rand()%(n-2)+2;//生成随机数 
        x=pow_mod(x,u,n);
        pre=x;
        for(j=0;j<k;j++){
            x=mul_mod(x,x,n);
            if(x==1&&pre!=1&&pre!=(n-1))//二次探测判断 
                return false;
            pre=x;
        }
        if(x!=1) return false;//用费马小定理判断 
    }
    return true;
}
int main(){
    LL a,b,ans=0;
    scanf("%lld%lld",&a,&b);
    if(a>=b)	swap(a,b);
    for(LL i=a;i<=b;i++)
    	if(Miller_Rabin(i))
    		ans+=i;
    printf("%lld\n",ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/queque_heiya/article/details/105931382
今日推荐