BZOJ5323:[JXOI2018]遊戲

傳送門
不難發現,全部不能被其餘數篩掉的數是必定要選的,只有選了這些數字才能結束
假設有 \(m\) 個,枚舉結束時間 \(x\),答案就是 \(\sum \binom{x-1}{m-1}m!(n-m)!x\)
埃氏篩法便可求出 \(m\)php

# include <bits/stdc++.h>
using namespace std;
typedef long long ll;

const int maxn(1e7 + 5);
const int mod(1e9 + 7);

inline void Inc(int &x, const int y) {
    x = x + y >= mod ? x + y - mod : x + y;
}

int l, r, n, m, ans, fac[maxn], inv[maxn];
bitset <maxn> vis;

int main() {
    int i, j, k;
    scanf("%d%d", &l, &r), n = r - l + 1;
    if (l == 1) {
        for (k = i = 1; i < n; ++i) k = (ll)k * i % mod;
        ans = (ll)n * (n + 1) / 2 % mod * k % mod;
        return printf("%d\n", ans), 0;
    }
    for (i = l; i <= r; ++i)
        if (!vis[i]) for (++m, j = i; j <= r; j += i) vis[j] = 1;
    inv[0] = inv[1] = fac[0] = fac[1] = 1;
    for (i = 2; i <= n; ++i) inv[i] = (ll)(mod - mod / i) * inv[mod % i] % mod;
    for (i = 2; i <= n; ++i) fac[i] = (ll)fac[i - 1] * i % mod, inv[i] = (ll)inv[i] * inv[i - 1] % mod;
    for (i = m; i <= n; ++i) Inc(ans, (ll)fac[i] * inv[i - m] % mod);
    ans = (ll)ans * m % mod * fac[n - m] % mod, printf("%d\n", ans);
    return 0;
}
相關文章
相關標籤/搜索