咦 Rank 7?
根号算法?也不能叫根号算法。。
令
H(n)
为我们划分的标准。(H(n)的表示好像在2015还是2014的国家集训队论文里这么写的)
若
p≥H(n)
,筛法找出
[1,109p]
中的比p小的质数,然后选择第N个数字。
p≤H(n)
,先找出
[1,p)
的质数,二分容斥。
至于
H(n)
的取值,并不会理论推导。。这个值按照经验设吧。。
取65好像是比较优的。
#include <cstdio>
#include <cstring>
#define rep(i,j,k) for(i=j;i<k;++i)
typedef long long ll;
const int C = 65, N = 1000000000;
bool v[20000000];
int pri[100], tot, n, p;
ll f(int mid, int p) {
int i, j, k; ll ret = mid, d, f;
rep(i,2,p) v[i] = 0;
tot = 0;
rep(i,2,p) {
if (!v[i]) pri[tot++] = i;
for (j = 0; j < tot && i * pri[j] < p; ++j) {
v[i * pri[j]] = 1;
if (i % pri[j] == 0) break;
}
}
for (k = 1; k < (1 << tot); ++k) {
d = 1, f = -1;
rep(i,0,tot) if (k & (1 << i)) {
d *= pri[i];
if (d > mid) break;
f *= -1;
}
ret -= f * mid / d;
}
return ret;
}
int work1() {
int ans = 0, l = 1, r = N / p;
while (l < r) {
int mid = l + r >> 1;
if (f(mid, p) < n) l = mid + 1;
else r = mid;
}
if (f(l, p) == n) ans = l * p;
return ans;
}
int work2() {
int ans = 0, len = N / p + 1, i, k = 1;
if (n == 1) ans = p;
rep(i,2,len) v[i] = 0;
rep(i,2,len) if (!v[i])
if (i < p)
for (ll j = (ll) i * i; j < len; j += i)
v[j] = 1;
else
if (++k == n) ans = i * p;
return ans;
}
int main() {
while (scanf("%d%d", &n, &p) != EOF)
printf("%d\n", p < C ? work1() : work2());
return 0;
}
3181: [Coci2012]BROJ
Description
求最小质因子等于p的第n小的正整数(恰好有n-1个最小质因子等于p且比它
小的正整数)。p一定是质数。若答案超过10^9则输出0。
Sample Input
2 3
Sample Output
9
HINT
1 <= n, p <= 10^9
Solution
To solve this for large values of
P
we will use modification of the sieve
of Eratosthenes. Size of our sieve will be
represent multiples of
P
. During the execution of this algorithm we can
find smallest prime factors or mark only multiples of prime numbers
smaller than
For smaller values of P we can binary search through
[1,109/P]
,
again looking at these numbers as the corresponding multiples of
P
.
For some number we must find the number of integers not greater and
relatively prime with that number. We can do this by using inclusionexclusion
principle with prime numbers less than
With careful implementation this solution can work for much larger
values of
P
than requested for this subtask.
We can also solve this task for smaller value of
periodic behaviour of smallest prime factors. Let
A(n)
be the smallest
prime factor of
n
,
of first k primes. For
A(n)≤B(k)
,
A(n+T(k))=A(n)
holds. So it’s
enough to know
A(n)
for
n≤T(k)
in order to find the
N
-th prime
who’s smallest prime factor is
Necessary skills: sieve of Eratosthenes, inclusion-exclusion principle
Category: number theory, combinatorics