POJ - 2480 Longge‘s problem (欧拉函数)

题目链接:点击这里

题目大意:
给定正整数 n ( 1 < n < 2 31 − 1 ) n(1<n<2^{31}-1) n(1<n<2311) ,求:
∑ i = 1 n gcd ⁡ ( i , n ) \sum_{i=1}^n\gcd(i,n) i=1ngcd(i,n)

题目分析:
∑ i = 1 n gcd ⁡ ( i , n ) \sum_{i=1}^n\gcd(i,n) i=1ngcd(i,n)
= ∑ d ∣ n ∑ i = 1 n [ gcd ⁡ ( i , n ) = d ] ⋅ d =\sum_{d|n}\sum_{i=1}^n[\gcd(i,n)=d]·d =dni=1n[gcd(i,n)=d]d
= ∑ d ∣ n d ∑ i = 1 n / d [ gcd ⁡ ( i / d , n / d ) = 1 ] =\sum_{d|n}d\sum_{i=1}^{n/d}[\gcd(i/d,n/d)=1] =dndi=1n/d[gcd(i/d,n/d)=1]
= ∑ d ∣ n d ⋅ φ ( n / d ) =\sum_{d|n}d·\varphi(n/d) =dndφ(n/d)
所以我们就可以枚举 n n n 的因子然后暴力求欧拉函数值即可,时间复杂度看似为 O ( n ) O(n) O(n) ,但是由于求欧拉函数时的质因子分解跑不满根号,所以时间复杂度为 O ( 可 过 ) O(可过) O()

具体细节见代码:

// Problem: Longge's problem
// Contest: Virtual Judge - POJ
// URL: https://vjudge.net/problem/POJ-2480
// Memory Limit: 65 MB
// Time Limit: 1000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

//#pragma GCC optimize(2)
//#pragma GCC optimize("Ofast","inline","-ffast-math")
//#pragma GCC target("avx,sse2,sse3,sse4,mmx")
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<queue>
// #include<unordered_map>
#define ll long long
#define inf 0x3f3f3f3f
#define Inf 0x3f3f3f3f3f3f3f3f
//#define int  ll
#define endl '\n'
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)
using namespace std;
int read()
{
	int res = 0,flag = 1;
	char ch = getchar();
	while(ch<'0' || ch>'9')
	{
		if(ch == '-') flag = -1;
		ch = getchar();
	}
	while(ch>='0' && ch<='9')
	{
		res = (res<<3)+(res<<1)+(ch^48);//res*10+ch-'0';
		ch = getchar();
	}
	return res*flag;
}
const int maxn = 1e6+5;
const int mod = 1e9+7;
const double pi = acos(-1);
const double eps = 1e-8;
ll n;
ll get_phi(int n)
{
	ll res = n;
	for(ll i = 2;i*i <= n;i++)
	{
		if(n%i) continue;
		res = res/i*(i-1);
		while(n%i == 0) n /= i;
	}
	if(n > 1) res = res/n*(n-1);
	return res;
}
int main()
{
	while(~scanf("%lld",&n))
	{
		ll res = 0;
		for(ll i = 1;i*i <= n;i++)
		{
			if(n%i == 0)
			{
				res += i*get_phi(n/i);
				if(i*i != n) res += (n/i)*get_phi(i);
			}
		}
		printf("%lld\n",res);
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值