HDU 3501 Calculation 2 (尤拉函式應用)

_TCgogogo_發表於2015-08-25


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
3 4 0
 
Sample Output
0 2
 
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);
    }
}





相關文章