f(n)
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 365 Accepted Submission(s): 221
Problem Description
This time I need you to calculate the f(n) . (3<=n<=1000000)
f(n)= Gcd(3)+Gcd(4)+…+Gcd(i)+…+Gcd(n).
Gcd(n)=gcd(C[n][1],C[n][2],……,C[n][n-1])
C[n][k] means the number of way to choose k things from n some things.
gcd(a,b) means the greatest common divisor of a and b.
f(n)= Gcd(3)+Gcd(4)+…+Gcd(i)+…+Gcd(n).
Gcd(n)=gcd(C[n][1],C[n][2],……,C[n][n-1])
C[n][k] means the number of way to choose k things from n some things.
gcd(a,b) means the greatest common divisor of a and b.
There are several test case. For each test case:One integer n(3<=n<=1000000). The end of the in put file is EOF.
For each test case:
The output consists of one line with one integer f(n).
The output consists of one line with one integer f(n).
3 26983
3 37556486
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2582
题目大意:求f(n)= Gcd(3)+Gcd(4)+…+Gcd(i)+…+Gcd(n),Gcd(n)=gcd(C[n][1],C[n][2],……,C[n][n-1])
题目分析:显然若n有两个以上的素因子则Gcd(n) = 1,若n=p^k则Gcd(n) = p,O(n)素数筛 + O(20 * primenum)处理p^k的数,预处理复杂度为O(n),查询直接O(1)
#include <cstdio>
#define ll long long
int const MAX = 1e6 + 5;
int p[MAX];
bool noprime[MAX];
ll num[MAX], ans[MAX];
void pre()
{
int pnum = 0;
for(int i = 2; i < MAX; i++)
{
num[i] = 1;
if(!noprime[i])
p[pnum ++] = i;
for(int j = 0; j < pnum && i * p[j] < MAX; j++)
{
noprime[i * p[j]] = true;
if(i % p[j] == 0)
break;
}
}
for(int i = 0; i < pnum; i++)
{
ll tmp = 1;
for(int j = 0; j <= 20; j++)
{
tmp = tmp * p[i];
if(tmp > MAX)
break;
num[tmp] = p[i];
}
}
for(int i = 3; i < MAX; i++)
ans[i] = ans[i - 1] + num[i];
}
int main()
{
pre();
int n;
while(scanf("%d", &n) != EOF)
printf("%lld\n", ans[n]);
}