結果

問題 No.8030 ミラー・ラビン素数判定法のテスト
ユーザー bal4u
提出日時 2019-05-12 17:30:26
言語 C(gnu17)
(gcc 15.2.0)
コンパイル:
gcc-15 -O2 -std=gnu17 -Wno-error=implicit-function-declaration -Wno-error=implicit-int -Wno-error=incompatible-pointer-types -Wno-error=int-conversion -DONLINE_JUDGE -o a.out _filename_ -lm
実行:
./a.out
結果
WA  
実行時間 -
コード長 1,795 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 236 ms
コンパイル使用メモリ 40,648 KB
最終ジャッジ日時 2026-02-22 03:22:16
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 5 WA * 5
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

// yukicoder 3030 ミラー・ラビン素数判定法のテスト
// 2019.5.12 bal4u

#include <stdio.h>
#include <stdlib.h>

typedef long long ll;
typedef unsigned long long ull;

//// 高速入出力
#if 1
#define gc() getchar_unlocked()
#define pc(c) putchar_unlocked(c)
#else
#define gc() getchar()
#define pc(c) putchar(c)
#endif

int in() {   // 非負整数の入力
	int n = 0, c = gc();
	do n = 10 * n + (c & 0xf), c = gc(); while (c >= '0');
	return n;
}

void ins(char *s) {  // 文字列の入力 スペース以下の文字で入力終了
	do *s = gc();
	while (*s++ > ' ');
	*(s-1) = 0;
}

long long s2ll(char *s) {   // 非負整数への変換
	long long n = 0;
	while (*s) n = 10*n + (*s++ & 0xf);
	return n;
}

void outs(char *s) { while (*s) pc(*s++); }  // 文字列の表示

//// ラビン素数テスト
ull powmod(ull a, ull k, ull n)
{
	ull p, bit;

	p = 1; for (bit = 0x8000000000000000ULL; bit > 0; bit >>= 1) {
		if (p > 1) p = (__int128_t)p*p % n;
		if (k & bit) p = (__int128_t)p*a % n;
	}
	return p % n;
}

int suspect(int b, ull n)
{
	int i;
	ull t, u, x0, x1;

	u = n - 1, t = 0; while ((u & 1) == 0) u >>= 1, t++;
	x0 = powmod(b, u, n);
	for (i = 1; i <= t; i++) {
		x1 = (__int128_t)x0*x0 % n;
		if (x1 == 1 && x0 != 1 && x0 != n-1) return 0;
		x0 = x1;
	}
	return x1 == 1;
}

int miller_rabin(ull n) {
	ull a, r, k, m;
	int p, t;
	
	if (n <= 1) return 0;
	if (n == 2 || n == 3) return 1;
	if ((n & 1) == 0) return 0;
	if (!suspect(2, n)) return 0;
	if (n <= 1000000) {
		if (!suspect(3, n)) return 0;
	} else {
		if (!suspect(7, n)) return 0;
		if (!suspect(61, n)) return 0;
	}
	return 1;
}

char s[25];

int main()
{
	int n;
	long long x;
	
	n = in(); while (n--) {
		ins(s), outs(s), pc(' ');
		pc('0' + miller_rabin(s2ll(s))), pc('\n');
	}
	return 0;
}
0