FJUT3565 最大公约数之和(容斥)题解

时间:2024-10-04 14:03:32

题意:给n,m,求出FJUT3565 最大公约数之和(容斥)题解

思路:题意为求出1~m所有数和n的gcd之和。显然gcd为n的因数。我们都知道gcd(a,b)= c,那么gcd(a/c,b/c)= 1。也就是说我们枚举n所有的因数k,然后去找1~m/k中和n/k互质的个数就是gcd为k的个数。这个直接容斥就行。

代码:

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<stdio.h>
#include<string.h>
#include<queue>
#include<cmath>
#include<map>
#include<set>
#include<vector>
using namespace std;
#define inf 0x3f3f3f3f
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define mem(a,b) memset(a,b,sizeof(a));
#define lowbit(x) x&-x;
typedef long long ll;
typedef unsigned long long ull;
const double eps = 1e-;
const int maxn = 1e5+;
const ll mod = 1e8+;
ll prime[maxn], p[maxn], pn;
void init(){
pn = ;
memset(prime, , sizeof(prime));
for(ll i = ; i < maxn; i++){
if(!prime[i]){
p[pn++] = i;
for(ll j = i * i; j < maxn; j += i)
prime[j] = ;
}
}
}
ll y[maxn], tot;
ll solve(ll r, ll n){ //返回1~r和n的gcd为1个数
tot = ;
ll N = n;
for(int i = ; p[i] * p[i] <= N && i < pn; i++){
if(N % p[i] == ){
y[tot++] = p[i];
while(N % p[i] == )
N /= p[i];
}
}
if(N > ) y[tot++] = N;
ll num = ;
for(ll i = ; i < ( << tot); i++){
ll val = , times = ;
for(ll j = ; j < tot; j++){
if(( << j) & i){
times++;
val *= y[j];
}
}
if(times & ){
num += r / val;
}
else{
num -= r / val;
}
}
return r - num;
} int main(){
ll n, m, num, ans = , cnt = , temp;
init();
scanf("%lld%lld", &n, &m);
for(ll i = ; i <= sqrt(n); i++){
if(n % i == ){
num = solve(m / i, n / i);
ans += num * i;
cnt += num;
if(i * i != n){
temp = n / i;
num = solve(m / temp, n / temp);
ans += num * temp;
cnt += num;
}
}
}
num = solve(m / n, );
ans += num * n;
cnt += num;
ans += m - cnt;
printf("%lld\n", ans);
return ;
}