标签:hdu 欧拉函数
Calculation 2
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2989 Accepted Submission(s): 1234
Problem Description
Given a positive integer N, your task is to calculate the sum of the positive integers less than N which are not coprime to N. A is said to be coprime to B if A, B share no common positive divisors except
1.
Input
For each test case, there is a line containing a positive integer N(1 ≤ N ≤ 1000000000). A line containing a single 0 follows the last test case.
Output
For each test case, you should print the sum module 1000000007 in a line.
Sample Input
Sample Output
Author
GTmac
Source
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3501
题目大意:求小于n的与n不互质的数的和
题目分析:考虑到小于n的与n互质的数的和很好求,再用总和减掉即可,小于n的与n互质的数的和等于n*phi[n] / 2,phi[n]为n对应的欧拉函数值,证明如下:
设gcd(n, i) == 1,则有gcd(n, n - i) == 1
这里可以反证:假设存在一个k != 1,gcd(n, n - i) == k,则有n%k == 0且(n - i) % k == 0即(n % k - i % k) % k == 0,得到(i % k) % k == 0
因此i必然是k的倍数,所以gcd(n, i) == k,这与gcd(n, i) == 1冲突,因此对于gcd(n, i) == 1,有gcd(n, n - i) == 1,所以与n互质的两对数相加为n,又与n互质的总个数为phi[n],注意这里不会出现n == 2*i 的情况因为出了2,phi[i]都为偶数
所以小于n的与n互质的数的和等于n*phi[n] / 2,所以最后答案为(n * (n - 1) / 2 - n*phi[n] / 2) % MOD,求单个phi的复杂度为sqrt((n)
#include <cstdio>
#include <cmath>
#define ll long long
int const MOD = 1e9 + 7;
int phi(int x)
{
int res = x;
for(int i = 2; i * i <= x; i++)
{
if(x % i == 0)
{
res = res / i * (i - 1);
while(x % i == 0)
x /= i;
}
}
if(x > 1)
res = res / x * (x - 1);
return res;
}
int main()
{
int n;
while(scanf("%d", &n) != EOF && n)
{
ll sum = (ll) n * (n - 1) / 2;
ll copsum = (ll) n * phi(n) / 2;
ll ans = sum - copsum;
printf("%I64d\n", ans % MOD);
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
HDU 3501 Calculation 2 (欧拉函数应用)
标签:hdu 欧拉函数
原文地址:http://blog.csdn.net/tc_to_top/article/details/47981359