51nod 1040最大公约数和(欧拉函数)

题目来源:  rihkddd
基准时间限制:1 秒 空间限制:131072 KB 分值: 80  难度:5级算法题
 收藏
 关注
给出一个n,求1-n这n个数,同n的最大公约数的和。比如:n = 6
1,2,3,4,5,6 同6的最大公约数分别为1,2,3,2,1,6,加在一起 = 15
 
Input
1个数N(N <= 10^9)
Output
公约数之和
Input示例
6
Output示例
15
思路:
目的是求∑(i= 1,n) gcd( i , n );
gcd( i , n ) = x,表示x是n的因子。稍作变形gcd( i / x , n / x) = 1,
看到这个式子可以想到欧拉函数,也就是求比n/x小的与其互质的个数。
因为这些书和n/x互质,乘上x后与n的最大公约数只有x。
也就是说我们先求出每个因子,然后计算每个因子有多少贡献即可。
 
 
/*
 * Author:  sweat123
 * Created Time:  2016/6/27 14:01:46
 * File Name: main.cpp
 */
#include<set>
#include<map>
#include<queue>
#include<stack>
#include<cmath>
#include<string>
#include<vector>
#include<cstdio>
#include<time.h>
#include<cstring>
#include<iostream>
#include<algorithm>
#define INF 1<<30
#define MOD 1000000007
#define ll long long
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define pi acos(-1.0)
using namespace std;
const int MAXN = 1000000;
int n;
ll ef(int n) 
{ 
    ll cnt = n; 
    int i; 
    for(i = 2; i * i <= n; i++){ 
        if(n % i == 0) 
        { 
            cnt -= cnt / i;      //   (x-x/p1) *(1-1/p2)*(1-1/p3)*(1-1/p4).....
            while(n % i == 0) 
                n /= i; 
        } 
    }
    if(n > 1) cnt -= cnt / n;
    return cnt; 
} 

int main(){
    while(~scanf("%d",&n)){
        ll ans = 0;
        for(int i = 1; i <= (int)sqrt(n); i++){
            if(n % i == 0){
                ans += ef(n / i) * i;
                if(n / i != i){
                    ans += ef(i) * (n / i);   
                }
            }
        } 
        printf("%lld\n",ans);
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/sweat123/p/5620086.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值