結果

問題 No.3030 ミラー・ラビン素数判定法のテスト
ユーザー furafura
提出日時 2020-12-11 17:42:34
言語 C++17
(gcc 13.2.0 + boost 1.83.0)
結果
AC  
実行時間 677 ms / 9,973 ms
コード長 879 bytes
コンパイル時間 4,176 ms
コンパイル使用メモリ 199,396 KB
実行使用メモリ 4,384 KB
最終ジャッジ日時 2023-08-10 16:27:17
合計ジャッジ時間 4,172 ms
ジャッジサーバーID
(参考情報)
judge12 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,380 KB
testcase_01 AC 1 ms
4,380 KB
testcase_02 AC 1 ms
4,380 KB
testcase_03 AC 2 ms
4,380 KB
testcase_04 AC 330 ms
4,380 KB
testcase_05 AC 311 ms
4,384 KB
testcase_06 AC 49 ms
4,380 KB
testcase_07 AC 49 ms
4,384 KB
testcase_08 AC 48 ms
4,380 KB
testcase_09 AC 677 ms
4,380 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>

#define rep(i,n) for(int i=0;i<(n);i++)

using namespace std;
using lint=long long;

random_device seed_gen;
mt19937 rng(seed_gen());

lint modpow(lint a,lint k,lint m){
	lint r=1%m;
	for(lint x=a%m;k>0;k>>=1,x=__int128(x)*x%m) if(k&1) r=__int128(r)*x%m;
	return r;
}

bool Miller_Rabin(lint n,int k=20){
	if(n<=1)   return false;
	if(~n&1)   return n==2;
	if(n%3==0) return n==3;

	int s=0; // n-1 = 2^s * d (d: odd)
	lint d=n-1;
	while(~d&1) s++, d>>=1;

	while(k--){
		lint a=rng()%(n-3)+2;
		lint x=modpow(a,d,n);
		if(x==1 || x==n-1) continue;
		bool b=false;
		for(int r=1;r<s;r++){
			x=__int128(x)*x%n;
			if(x== 1 ) return false;
			if(x==n-1){ b=true; break; }
		}
		if(!b) return false;
	}

	return true;
}

int main(){
	int q; scanf("%d",&q);
	rep(_,q){
		lint x; scanf("%lld",&x);
		printf("%lld %d\n",x,!!Miller_Rabin(x));
	}
	return 0;
}
0