码迷,mamicode.com
首页 > 其他好文 > 详细

Hdu3501容斥原理

时间:2015-08-13 21:52:05      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:

题意:问小于n且不与n互质的数的和是多少。

容斥原理求出和n互质的和,然后用 n*(n-1)/2 减以下,注意溢出。

#pragma comment(linker,"/STACK:102400000,102400000") 
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<iostream>
#include<string>
#include<queue>
#include<stack>
#include<list>
#include<stdlib.h>
#include<algorithm>
#include<vector>
#include<map>
#include<cstring>
#include<set>
using namespace std;
typedef long long LL;
const LL mod = 1000000007;
LL sum(LL n)// 可能越界
{
    LL t = n; LL t1 = n+1;
    if(t&1) t1/=2; 
    else t/=2;
    return t*t1%mod;
}

LL ans;
vector<LL> q;
void dfs(LL x, LL pre, LL flag, LL key)
{
    if (x == q.size()) {
    //  cout << pre << " JIi" << endl;
        if (flag) ans += pre*sum(key / pre);
        else ans -= pre*sum(key / pre);
        ans = (ans+mod)%mod;
     //   cout<<ans<<endl;
        return;
    }
    dfs(x + 1, pre, flag, key);
    dfs(x + 1, pre*q[x], flag ^ 1, key);
}



void gao(LL n)
{
    q.clear();
    LL t = n;
    ans = 0;
    for (LL i = 2; i*i <= t; i++) {
        if (t%i) continue;
        while (t%i == 0) t /= i;
        q.push_back(i);
    }
    if (t > 1) q.push_back(t);
    dfs(0, 1, 1, n - 1);
    LL k = sum(n-1);
    k-=ans;
    k%=mod; // 可能超过mod
    if(k<0) k = (k+mod)%mod;
    cout << k << endl;
}

int main()
{
    LL n;
    while (scanf("%I64d", &n)!=EOF && n ) {
        gao(n);
    }
    return 0;
}

 

Hdu3501容斥原理

标签:

原文地址:http://www.cnblogs.com/yigexigua/p/4728423.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!