結果

問題 No.12 限定された素数
ユーザー te-shte-sh
提出日時 2017-04-14 12:12:50
言語 D
(dmd 2.107.1)
結果
AC  
実行時間 59 ms / 5,000 ms
コード長 1,276 bytes
コンパイル時間 1,127 ms
コンパイル使用メモリ 113,768 KB
実行使用メモリ 6,292 KB
最終ジャッジ日時 2023-09-03 12:48:20
合計ジャッジ時間 3,620 ms
ジャッジサーバーID
(参考情報)
judge11 / judge15
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 51 ms
5,960 KB
testcase_01 AC 50 ms
5,688 KB
testcase_02 AC 50 ms
5,228 KB
testcase_03 AC 59 ms
5,752 KB
testcase_04 AC 50 ms
4,716 KB
testcase_05 AC 52 ms
5,488 KB
testcase_06 AC 53 ms
6,292 KB
testcase_07 AC 55 ms
4,944 KB
testcase_08 AC 49 ms
4,904 KB
testcase_09 AC 51 ms
6,016 KB
testcase_10 AC 51 ms
5,220 KB
testcase_11 AC 57 ms
5,452 KB
testcase_12 AC 55 ms
6,008 KB
testcase_13 AC 52 ms
5,216 KB
testcase_14 AC 50 ms
4,956 KB
testcase_15 AC 52 ms
5,448 KB
testcase_16 AC 58 ms
5,224 KB
testcase_17 AC 50 ms
4,936 KB
testcase_18 AC 51 ms
5,184 KB
testcase_19 AC 51 ms
4,728 KB
testcase_20 AC 50 ms
5,228 KB
testcase_21 AC 50 ms
5,204 KB
testcase_22 AC 50 ms
5,164 KB
testcase_23 AC 50 ms
6,012 KB
testcase_24 AC 50 ms
5,212 KB
testcase_25 AC 52 ms
5,204 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import std.algorithm, std.conv, std.range, std.stdio, std.string;

void main()
{
  auto n = readln.chomp.to!size_t;
  auto ai = readln.split.to!(int[]);
  writeln(calc(ai));
}

int calc(int[] ai)
{
  auto ma = 5_000_000;

  auto pi = primes(ma);
  auto s = ai.map!toBitNum.fold!"a | b";
  auto t = ~s & ((1 << 10) - 1);

  auto r = -1, i = 0;
  while (i < pi.length) {
    while (toBitNum(pi[i]) & t) {
      if (++i >= pi.length) return r;
    }

    auto j = i;
    while (!(toBitNum(pi[j]) & t)) {
      if (j++ >= pi.length - 1) break;
    }

    if (pi[i..j].map!toBitNum.fold!"a | b" == s) {
      auto p1 = i == 0 ? 1 : pi[i - 1] + 1;
      auto p2 = j == pi.length ? ma : pi[j] - 1;
      r = max(r, p2 - p1);
    }

    i = j + 1;
  }

  return r;
}

int toBitNum(int a)
{
  if (a == 0) return 1;

  int r = 0;
  for (; a != 0; a /= 10)
    r |= (1 << a % 10);
  return r;
}

pure int[] primes(int n)
{
  import std.math, std.bitmanip;

  auto sieve = BitArray();
  sieve.length((n + 1) / 2);
  sieve = ~sieve;

  foreach (p; 1..((n.to!real.sqrt.to!int - 1) / 2 + 1))
    if (sieve[p])
      for (auto q = p * 3 + 1; q < (n + 1) / 2; q += p * 2 + 1)
        sieve[q] = false;

  auto r = sieve.bitsSet.map!(to!int).map!("a * 2 + 1").array;
  r[0] = 2;

  return r;
}
0