hdu 3501
题意:求小于n的所有不与n互素的数的和。
思路:本来想着这个题可以和hdu 5514一样用容斥搞,但是tle了。。
对于一个小于n的正整数i,如果i与n互素,那么n-i也是与n互素;如果i不与n互素,那么n-i也一定不与n互素。这个很容易证明。
所以我们很容易可以发现对于n(n>2)来说,与它互素的数都是成对存在的,并且存在
ϕ(n)/2
对组合和是n,这样就可以求解了。
/****************************************************
>Created Date: 2015-11-04-12.38.37
>My Soul, Your Beats!
****************************************************/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <cmath>
#include <iostream>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <algorithm>
using namespace std;
typedef long long LL;
const int INF = 1 << 30;
const long long LINF = 1LL << 50;
const int MAXM = 1e5 + 5;
const int MAXN = 1e5 + 5;
const double PI = acos(-1.0);
const double eps = 1e-6;
const int MOD = 1e9 + 7;
int eular(int a){
int ret = a;
for(int i = 2; i * i <= a; i++){
if(a % i == 0){
ret = ret / i * (i - 1);
while(a % i == 0) a /= i;
}
}
if(a > 1) ret = ret / a * (a - 1);
return ret;
}
int main(){
#ifndef ONLINE_JUDGE
//freopen("in.in", "r", stdin);
#endif
LL n;
while(cin >> n && n){
LL phi = eular(n);
LL ans = n * (n - 1) / 2;
ans = (ans - phi * n / 2) % MOD;
cout << ans << endl;
}
return 0;
}
本文解析了HDU3501题目,该题要求计算小于n的所有不与n互质的数之和。通过分析发现,与n互质的数成对出现,利用欧拉函数优化计算过程。
371

被折叠的 条评论
为什么被折叠?



