結果

問題 No.774 tatyamと素数大富豪
ユーザー bal4ubal4u
提出日時 2019-05-12 20:30:13
言語 C
(gcc 12.3.0)
結果
AC  
実行時間 1,086 ms / 2,000 ms
コード長 1,696 bytes
コンパイル時間 1,048 ms
コンパイル使用メモリ 30,056 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-09-18 14:50:11
合計ジャッジ時間 5,666 ms
ジャッジサーバーID
(参考情報)
judge15 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1,086 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,376 KB
testcase_04 AC 1 ms
4,376 KB
testcase_05 AC 0 ms
4,376 KB
testcase_06 AC 1 ms
4,376 KB
testcase_07 AC 1 ms
4,376 KB
testcase_08 AC 0 ms
4,376 KB
testcase_09 AC 17 ms
4,376 KB
testcase_10 AC 1 ms
4,380 KB
testcase_11 AC 6 ms
4,380 KB
testcase_12 AC 487 ms
4,376 KB
testcase_13 AC 247 ms
4,376 KB
testcase_14 AC 4 ms
4,376 KB
testcase_15 AC 9 ms
4,380 KB
testcase_16 AC 5 ms
4,380 KB
testcase_17 AC 3 ms
4,380 KB
testcase_18 AC 5 ms
4,380 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

// yukicoder 774 tatyamと素数大富豪
// 2019.5.12 bal4u

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

typedef long long ll;
typedef unsigned long long ull;

//// ラビン素数テスト
#define mulmod128(a,b,n) ((__int128_t)a*b % n)

ull powmod(ull a, ull k, ull n)
{
	ull bit = 0x2000000000000000LL, p = 1;
	while (bit) {
		if (p > 1) p = mulmod128(p, p, n);
		if (k & bit) p = mulmod128(p, a, n);
		bit >>= 1;
	}
	return p;
}

unsigned xorshift(int id) {
  static unsigned y = 2463534242;
  y = y ^ (y << 13), y = y ^ (y >> 17), y = y ^ (y << 5);
  return y;
}

ull gcd(ull a, ull b) {
	ull r;
	while (b != 0) r = a % b, a = b, b = r;
	return a;
}

int suspect(ull n) {
	int i, j, b;
	ull t, u, x;

	u = n-1, t = 0; while ((u & 1) == 0) u >>= 1, t++;
	for (j = 0; j < 6; j++) {
		do b = xorshift(j) % n;
		while (gcd(b, n) > 1);

		x = powmod(b, u, n);
		if (x == 1 || x == n-1) continue;
		for (i = 1; i < t; i++) {
			x = mulmod128(x, x, n);
			if (x == 1) return 0;
			if (x == n-1) break;
		}
		if (i == t) return 0;
	}
	return 1;
}

int miller_rabin(ull n) {
	if (n <= 1) return 0;
	if (n == 2 || n == 3) return 1;
	if ((n & 1) == 0) return 0;
	return suspect(n);
}

int a[15], n;
int t[15], f[15];
ll ans = -1;

void rec(int id) {
	int i, pre;
	long long x;
	
	if (id == n) {
		x = 0; for (i = 0; i < n; i++) {
			x *= 10; if (t[i] >= 10) x *= 10;
			x += t[i];
		}
		if (miller_rabin(x) && x > ans) ans = x;
		return;
	}
	pre = -1;
	for (i = 0; i < n; i++) {
		if (f[i] || a[i] == pre) continue;
		f[i] = 1, t[id] = pre = a[i];
		rec(id+1);
		f[i] = 0;
	}
}

int main()
{
	int i;
	scanf("%d", &n);
	for (i = 0; i < n; i++) scanf("%d", a+i);
	rec(0);
	printf("%lld\n", ans);
	return 0;
}
0