QOJ.ac

QOJ

IDProblemSubmitterResultTimeMemoryLanguageFile sizeSubmit timeJudge time
#589949#249. Miller Rabin 算法lanhuoWA 9ms3600kbC++171.5kb2024-09-25 20:47:072024-09-25 20:47:08

Judging History

你现在查看的是最新测评结果

  • [2024-09-25 20:47:08]
  • 评测
  • 测评结果:WA
  • 用时:9ms
  • 内存:3600kb
  • [2024-09-25 20:47:07]
  • 提交

answer

#include<bits/stdc++.h>
using namespace std;
//#pragma GCC optimize(2)
//#pragma GCC optimize(3,"Ofast","inline")
typedef long long ll;
#define pll pair<ll,ll>
ll n;
ll prime[10]={2,3,5,7,11,13,17,19,23,29};
ll Quick_Multiply(ll a,ll b,ll c){
    ll ans=0,res=a;
    while(b){
        if(b&1)ans=(ans+res)%c;
        res=(res+res)%c;
        b>>=1;
    }
    return ans;
}
ll Quick_Power(ll a,ll b,ll m){
    ll ans=1;
    while(b){
        if(b&1)ans=ans*a%m;
        a=a*a%m;
        b>>=1;
    }
    return ans;
}
bool Miller_Rabin(ll x){ //判断素数
    ll i,j,k;
    ll s=0,t=x-1;
    if(x==2)return true; //2是素数
    if(x<2||!(x&1))return false;  //如果x是偶数或者是0,1,那它不是素数
    while(!(t&1)){ //将x-1分解成(2^s)*t的样子
        s++;
        t>>=1;
    }
    for(i=0;i<10&&prime[i]<x;i++){ //随便选一个素数进行测试
        ll a=prime[i];
        ll b=Quick_Power(a,t,x); //先算出a^t
        for(j=1;j<=s;j++){ //然后进行s次平方
            k=Quick_Multiply(b,b,x); //求b的平方
            if(k==1&&b!=1&&b!=x-1)return false;
            b=k;
        }
        if(b!=1)return false; //用费马小定理判断
    }
    return true; //如果进行多次测试都是对的,那么x就很有可能是素数
}
void solve(){
	if(Miller_Rabin(n))cout<<"Y\n";
	else cout<<"N\n";
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    while(cin>>n)solve();
    return 0;
}

Details

Tip: Click on the bar to expand more detailed information

Test #1:

score: 0
Wrong Answer
time: 9ms
memory: 3600kb

input:

996581938833575363
971646509461160317
773155992127361153
161603952726515268
540879144500456953
476831214764178553
784255927154201144
671096087619405061
805545190025269709
339546334309245137
337726347922962343
222956293307015293
809183111090275843
799050063298926344
691718101820598109
646220213113313...

output:

N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
...

result:

wrong answer 2nd lines differ - expected: 'Y', found: 'N'