結果

問題 No.407 鴨等素数間隔列の数え上げ
ユーザー はむ吉🐹
提出日時 2016-07-09 18:27:30
言語 C++11(廃止可能性あり)
(gcc 13.3.0)
結果
RE  
実行時間 -
コード長 2,180 bytes
コンパイル時間 851 ms
コンパイル使用メモリ 61,160 KB
実行使用メモリ 13,184 KB
最終ジャッジ日時 2024-10-13 10:20:42
合計ジャッジ時間 2,561 ms
ジャッジサーバーID
(参考情報)
judge5 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 5
other AC * 26 RE * 5
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <cassert>
#include <ciso646>
#include <cstdlib>
#include <iostream>
#include <vector>


// テストケース検証用の定数
constexpr int MIN_N = 3;
constexpr int MAX_N = 1000000;
constexpr int MIN_L = 1;
constexpr int MAX_L = 5000000;


// Eratosthenesの篩により、素数表をつくる
std::vector<bool> sieve_of_eratosthenes(int end) {
    assert(end > 1);
    std::vector<bool> is_prime(end, true);
    is_prime[0] = false;
    is_prime[1] = false;
    for (int i = 2; i < end; i++)
    {
        if (is_prime[i]) {
            for (int j = 2 * i; j < end; j += i)
            {
                is_prime[j] = false;
            }
        }
    }
    return is_prime;
}


// 素数計数関数の表をつくる
// 上のEratosthenesの篩とは区間のとりかたが異なることに注意
std::vector<int> pcf_table(int last) {
    assert(last >= 1);
    auto is_prime = sieve_of_eratosthenes(last + 1);
    std::vector<int> pcf(last + 1);
    // 漸化式pcf[i] = pcf[i - 1] + f(i)で計算していく
    // ただしiが素数ならばf(i) = 1、さもなければf(i) = 0
    // 単純なボトムアップの動的計画法による
    for (int i = 1; i <= last; i++)
    {
        pcf[i] = pcf[i - 1] + int(is_prime[i]);
    }
    return pcf;
}


// 鴨等素数間隔列を数える
long long count_seqs(int n, int l) {
    // 初項x0のとりうる最大値
    auto x0_max = l - n + 1;
    if (x0_max < 0)
    {
        return 0;
    }
    // x0が決まれば、dの最大値d_maxが決まる
    auto d_max = [&](int x0) {return (l - x0) / (n - 1); };
    // max d_max(x0) = d_max(0)
    // そこまでの素数計数関数の表をつくる
    auto pcf = pcf_table(d_max(0));
    // 答えはintにおさまらないことがある
    long long answer = 0;
    for (auto x0 = 0; x0 <= x0_max; x0++)
    {
        answer += pcf[d_max(x0)];
    }
    return answer;
}


int main() {
    std::cin.tie(nullptr);
    std::ios::sync_with_stdio(false);
    int n, l;
    std::cin >> n >> l;
    assert(MIN_N <= n and n <= MAX_N);
    assert(MIN_L <= l and l <= MAX_L);
    std::cout << count_seqs(n, l) << std::endl;
    return EXIT_SUCCESS;
}
0