HDU 2582 f(n) (組合數的gcd)

_TCgogogo_發表於2015-09-11


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.
 
Input
There are several test case. For each test case:One integer n(3<=n<=1000000). The end of the in put file is EOF.
 
Output
For each test case:
The output consists of one line with one integer f(n).
 
Sample Input
3 26983
 
Sample Output
3 37556486
 
Source
 
題目連結: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]);
}

 

相關文章