計算 S(n) = ⌊( (3n+6)! + 1 ) / (3n+7) ⌋ - ⌊( (3n+6)! ) / (3n+7) ⌋ 對於 n = 1..N 的前綴和。多組測試,N ≤ 1,000,000。
p = 3n+7。若 p 為合數,則 p = ab (a,b>1),a,b ≤ 3n+6,故 (3n+6)! ≡ 0 (mod p),原式 = 0。p 為素數,由威爾遜定理 (p-1)! ≡ -1 (mod p),即 (3n+6)! ≡ -1 (mod p),則 (3n+6)! + 1 ≡ 0 (mod p),原式 = 1。結論:第 n 項 = 1 當 3n+7 為素數,否則 0。
isPrime[3N+7] 至 3,000,007。ans[i] = ans[i-1] + isPrime[3*i+7]。O(1) 回答。#include
using namespace std;
const int MAXN = 1000000;
const int LIM = 3*MAXN + 7;
bool isPrime[LIM+1];
int ans[MAXN+1];
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
fill(isPrime, isPrime+LIM+1, true);
isPrime[0] = isPrime[1] = false;
for (int i = 2; i*i <= LIM; ++i)
if (isPrime[i])
for (int j = i*i; j <= LIM; j += i)
isPrime[j] = false;
for (int i = 1; i <= MAXN; ++i)
ans[i] = ans[i-1] + (isPrime[3*i+7] ? 1 : 0);
int T; cin >> T;
while (T--) {
int n; cin >> n;
cout << ans[n] << '\n';
}
return 0;
}
O(LIM log log LIM) ≈ 3e6,極快。O(N)。O(1)。isPrime[3e6] ≈ 3MB,ans[1e6] ≈ 4MB。(p-1)! mod p。