【hdu3501】求[1,n-1]与n不互质的所有数之和(单个欧拉函数求法+[1,n]和n互质的数之和公式----模版题)

题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=3501

题意


求[1,n-1]内与n不互质的所有数之和

 

解题思路


注意是[1,n-1],不是[1,n]!!

  • 欧拉函数的普通表达式:

  • [1,n]和n互质的数之和公式为n*\varphi (n)/2其中\varphi (n)是n对应的欧拉函数值

公式正确性证明见:https://blog.csdn.net/clover_hxy/article/details/53152358gcd(n,i)=1\Leftrightarrowgcd(n,n-i)=1)

 

ac代码


#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <ctype.h>
#include <set>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <sstream>
#define  maxn 10000
typedef long long ll;
const ll mod=1e9+7;
using namespace std;
ll euler(ll n)
{
    ll ans=n;
    for(ll i=2;i*i<=n;i++)
    {
        if(n%i==0)
        {
            ans=ans/i*(i-1);
            while(n%i==0) n/=i;
        }
    }
    if(n!=1) ans=ans/n*(n-1);
    return ans;
}
int main()
{
    //freopen("/Users/zhangkanqi/Desktop/11.txt","r",stdin);
    ll x;
    while(scanf("%lld",&x)&& x!=0)
    {

        if(x==1) printf("0\n");
        else {
            ll ans=x*(x-1)/2-x*euler(x)/2;//注意是[1,n-1]
            printf("%lld\n", ans % mod);//求不与x互质的数的和
        }
    }
    return 0;

}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值