HDU 3501 Calculation 2 (欧拉函数应用)

本文介绍了一道算法题的解决方法,该题要求计算小于N的所有与N不互质的正整数之和。文章详细分析了如何通过已知的与N互质的数的和来间接求解目标问题,并提供了完整的代码实现。


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);
    }
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值