結果

問題 No.3030 ミラー・ラビン素数判定法のテスト
ユーザー do2424_titechdo2424_titech
提出日時 2019-06-18 01:17:33
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 6,096 ms / 9,973 ms
コード長 2,077 bytes
コンパイル時間 1,390 ms
コンパイル使用メモリ 167,480 KB
実行使用メモリ 5,376 KB
最終ジャッジ日時 2024-04-28 09:24:41
合計ジャッジ時間 18,302 ms
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

#include <bits/stdc++.h>

unsigned long long small_sprp_base[] = { 2, 7, 61 };
unsigned long long big_sprp_base[] = { 2, 325, 9375, 28178, 450775, 9780504, 1795265022 };

unsigned long long ll_product(unsigned long long a, unsigned long long b, unsigned long long r) {
	unsigned long long ans = 0;
	while (a != 0) {
		if ((a & 1) == 1) {
			ans = (ans + b) % r;
		}
		b = (b << 1) % r;
		a >>= 1;
	}
	return ans;
}

unsigned long long ll_power(unsigned long long a, unsigned long long b, unsigned long long r) {
	unsigned long long ans = 1;
	while (b != 0) {
		if ((b & 1) == 1) {
			ans = ll_product(ans, a, r);
		}
		a = ll_product(a, a, r);
		b >>= 1;
	}
	return ans;
}

bool primality_test(unsigned long long num) {
	if (num == 2) {
		return true;
	}
	if ((num & 1) == 0 || num == 1) {
		return false;
	}
	unsigned long long d = (num - 1) >> 1;
	int s = 1;
	while ((d & 1) == 0) {
		d >>= 1;
		s++;
	}
	if (num < (1ull << 32)) {
		for (int k = 0; k < 3; k++) {
			bool is_prime = false;
			unsigned long long a = small_sprp_base[k];
			if (num > a) {
				unsigned long long r = ll_power(a, d, num);
				if (r == 1 || r == num - 1) {
					is_prime = true;
				}
				for (int i = 0; i < s; i++) {
					r = ll_product(r, r, num);
					if (r == num - 1) {
						is_prime = true;
					}
				}
				if (!is_prime) {
					return false;
				}
			}
		}
	}
	else {
		for (int k = 0; k < 7; k++) {
			bool is_prime = false;
			unsigned long long a = big_sprp_base[k];
			if (num > a) {
				unsigned long long r = ll_power(a, d, num);
				if (r == 1 || r == num - 1) {
					is_prime = true;
				}
				for (int i = 0; i < s; i++) {
					r = ll_product(r, r, num);
					if (r == num - 1) {
						is_prime = true;
					}
				}
				if (!is_prime) {
					return false;
				}
			}
		}
	}
	return true;
}

int main() {
	int n;
	std::cin >> n;
	for (int i = 0; i < n; i++) {
		unsigned long long hoge;
		std::cin >> hoge;
		std::cout << hoge << " " << std::flush;
		if (primality_test(hoge)) {
			std::cout << "1" << std::endl;
		}
		else {
			std::cout << "0" << std::endl;
		}
	}
	return 0;
}
0