結果

問題 No.3030 ミラー・ラビン素数判定法のテスト
ユーザー okok
提出日時 2019-09-04 09:57:01
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
WA  
実行時間 -
コード長 2,211 bytes
コンパイル時間 874 ms
コンパイル使用メモリ 97,696 KB
実行使用メモリ 5,376 KB
最終ジャッジ日時 2024-04-29 13:26:18
合計ジャッジ時間 2,406 ms
ジャッジサーバーID
(参考情報)
judge2 / judge4
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
5,248 KB
testcase_01 AC 2 ms
5,376 KB
testcase_02 AC 2 ms
5,376 KB
testcase_03 AC 2 ms
5,376 KB
testcase_04 WA -
testcase_05 WA -
testcase_06 WA -
testcase_07 WA -
testcase_08 WA -
testcase_09 WA -
権限があれば一括ダウンロードができます

ソースコード

diff #

#include<iostream>
#include<string>
#include<iomanip>
#include<cmath>
#include<vector>
#include<algorithm>

#include<ctime>
#include <random>
#include <limits>

using namespace std;

// #define int __int128
#define int long long
#define endl "\n"

// powerのオーバーフローに注意(素数が1~2^63のときには__int128などを使用すること)
//https://primes.utm.edu/prove/prove2_3.html

template<typename Type>
inline Type  product(Type  x, Type  n, Type mod){
	Type  ans = 0;
	while(n){
		if(n&1) ans += x;
		n >>= 1;
		x += x;
		x %= mod;
		ans %= mod;
	}
	return ans;
}

template<typename Type>
inline Type  power(Type  x, Type  n, Type mod){
	Type  ans = 1;
	while(n){
		if(n&1) ans *= x;
		// if(n&1) ans = product(ans,x,mod);
		n >>= 1;
		x *= x;
		// x = product(x,x,mod);
		x %= mod;
		ans %= mod;
	}
	return ans;
}

template<typename Type = __int128>
inline bool Miller_Rabin(Type num, long long k){
	if(num <= 1)        return false;
	else if(num == 2)   return true;
	else if(num%2 == 0) return false; 
	
	Type  s = 0, d = 0;
	vector<int> div;
	
	if(false){ // num < 2^32
	// if(num < (1<<31)){ // num < 2^32
		div = {2,7,61};
	// } else if(num < (1<<63)){
	} else if(false){ // num < 2^63
		div = {2, 325, 9375, 28178, 450775, 9780504, 1795265022};
	} else {
		random_device rnd;
		mt19937 mt(rnd()); 
		// uniform_int_distribution<> rd(1,min((int)numeric_limits<int>::max(), num-1));
		for(long long i = 0; i < k; i++){
			// div.push_back(rd(mt));
			div.push_back(mt()%(num-1)+1);
		}
	}
	
	for(Type n = num-1;;){
		if(n%2){ 
			d = n; break;
		} else s++, n >>= 1;
	}
	
	for(Type  i = 0; i < div.size(); i++){
		Type  a = div[i], n = d, a2 = 1;
		bool flag = true;
		
		if(a >= num) break;
		
		a2 = power(a, d, num);
		
		if(a2 == 1) continue;
		
		for(Type r = 0, two = 1; r < s; r++, two <<= 1){
			a2 = power(a, two*d, num);
			
			if(a2 == num-1){
				flag = false;
				break;
			}
		}
		
		if(flag) return false;
	}
	
	return true;
}

signed main(){
	cin.tie(0);
	ios::sync_with_stdio(false);
	cout<<fixed<<setprecision(10);
	
	long long n;
	
	cin>>n;
	
	for(int i = 0; i < n; i++){
		long long x;
		cin>>x;
		
		cout<<x<<" "<<Miller_Rabin(x, 10)<<endl;
	}
	
	
	return 0;
}
0