Calculation 2 [HUD 3501]

容斥原理, 纠结好久, 求N以内和N不互质的所有数的和。

http://acm.hdu.edu.cn/showproblem.php?pid=3501

View Code
int64 tp[MM], mm;
void solve() {
    int64 i,j,k,ans=0,tmp=N,tt,t1,ret=1;
    for(i=mm=0;i<cnt;i++) {
        if(tmp%prm[i]==0) {
            tp[mm++]=prm[i];
            while(tmp%prm[i]==0) tmp/=prm[i];
        }
    }
    if(tmp>1) tp[mm++]=tmp;
//    for(i=0;i<mm;i++) printf("%I64d ",tp[i]); printf("\n");
    for(i=1;i<(1<<mm);i++) {
        for(k=j=0,ret=1;j<mm;j++) {
            if(i&(1<<j)) {
                ret=(ret*tp[j]);
                k++;
            }
        }
    //    printf("%I64d\n", ret);
        tt=N/ret; t1=((tt-1)*tt/2)%mod;
        t1=(ret*t1)%mod;
    //    printf("%I64d %I64d\n",ret,t1);
        if(k&1) ans=(ans+t1)%mod;
        else ans=(ans-t1)%mod;
    //    printf("%I64d %I64d\n",ret,ans);
    }
    if(ans<0) ans+=mod;
    printf("%I64d\n", ans);
} 
// 12 42
int main() {
    cnt=get_prime(33333);
    while(scanf("%I64d",&N),N) solve();
    return 0;
}
原文地址:https://www.cnblogs.com/zhang1107/p/3031856.html