HDU 3501 Calculation 2
一、题意
求解与不互质的数的和。
二、欧拉函数解法
定义:欧拉函数是小于的数中与互质的数的数目。
例如,因为均和互质。
利用欧拉函数即可求解,比小且与互素的数的总和为;
那么可以先求出的总和,然后减去即可。
#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ULL;
const ULL mod = 1000000007;
ULL euler(ULL n) {
ULL res = n, a = n;
for (ULL i = 2; i * i <= a; i++) {
if (a % i == 0) {
res = res / i * (i - 1);
while (a % i == 0) a /= i;
}
}
if (a > 1) res = res / a * (a - 1);
return res;
}
int main() {
ULL n;
while (~scanf("%llu", &n), n) {
ULL sum = n * (1 + n) / 2 - n, ans;
ans = sum - euler(n) * n / 2;
printf("%llu\n", ans % mod);
}
return 0;
}
三、分解质因数+容斥原理
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const LL mod = 1000000007;
int main() {
LL n, m;
while (cin >> m && m) {
if (m == 1) {
cout << "0" << endl;
continue;
}
n = m;
//分解质因数
vector<LL> p;
for (LL i = 2; i * i <= n; i++) {
if (n % i == 0) {
p.push_back(i);
while (n % i == 0)
n = n / i;
}
}
if (n > 1) p.push_back(n);
LL ans = 0;
for (int i = 1; i < (1 << p.size()); i++) {
int cnt = 0;
int t = 1;
for (int j = 0; j < p.size(); j++) {
if (i >> j & 1) {
cnt++;
t *= p[j];
}
}
LL num = (m - 1) / t;
LL tmp = (t + t * num) * num / 2;
if (cnt & 1)
ans += tmp;
else
ans -= tmp;
}
cout << ans % mod << endl;
}
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
2019-06-20 https跳http
2017-06-20 研修项目文件丢失的处理思路
2017-06-20 安装配置GitLab
2016-06-20 使用Nginx+FFMPEG搭建HLS直播转码服务器