# 【bzoj3944/bzoj4805】Sum/欧拉函数求和 杜教筛

bzoj3944

6
1
2
8
13
30
2333

1 1
2 0
22 -2
58 -3
278 -3
1655470 2

bzoj4805

bzoj3944：

#include <cstdio>
#include <map>
#include <utility>
#define N 3000010
using namespace std;
typedef long long ll;
map<ll , pair<ll , ll> > f;
map<ll , pair<ll , ll> >::iterator it;
ll phi[N] , mu[N] , prime[N] , tot , sumphi[N] , summu[N] , m = 3000000;
bool np[N];
void query(ll n , ll &ans1 , ll &ans2)
{
if(n <= m)
{
ans1 = sumphi[n] , ans2 = summu[n];
return;
}
it = f.find(n);
if(it != f.end())
{
ans1 = it->second.first , ans2 = it->second.second;
return;
}
ans1 = n * (n + 1) / 2 , ans2 = 1;
ll i , last , tmp1 , tmp2;
for(i = 2 ; i <= n ; i = last + 1)
{
last = n / (n / i) , query(n / i , tmp1 , tmp2);
ans1 -= (last - i + 1) * tmp1 , ans2 -= (last - i + 1) * tmp2;
}
f[n] = make_pair(ans1 , ans2);
}
int main()
{
int T;
ll n , i , j , ans1 , ans2;
np[1] = 1 , mu[1] = phi[1] = sumphi[1] = summu[1] = 1;
for(i = 2 ; i <= m ; i ++ )
{
if(!np[i]) prime[++tot] = i , phi[i] = i - 1 , mu[i] = -1;
for(j = 1 ; j <= tot && i * prime[j] <= m ; j ++ )
{
np[i * prime[j]] = 1;
if(i % prime[j] == 0)
{
phi[i * prime[j]] = phi[i] * prime[j] , mu[i * prime[j]] = 0;
break;
}
else phi[i * prime[j]] = phi[i] * (prime[j] - 1) , mu[i * prime[j]] = -mu[i];
}
sumphi[i] = sumphi[i - 1] + phi[i] , summu[i] = summu[i - 1] + mu[i];
}
scanf("%d" , &T);
while(T -- ) scanf("%lld" , &n) , query(n , ans1 , ans2) , printf("%lld %lld\n" , ans1 , ans2);
return 0;
}


bzoj4805：

#include <cstdio>
#include <map>
#define N 1600010
using namespace std;
typedef long long ll;
map<ll , ll> f;
map<ll , ll>::iterator it;
ll m = 1600000 , phi[N] , prime[N] , tot , sum[N];
bool np[N];
ll query(ll n)
{
if(n <= m) return sum[n];
it = f.find(n);
if(it != f.end()) return it->second;
ll ans = n * (n + 1) / 2 , i , last;
for(i = 2 ; i <= n ; i = last + 1) last = n / (n / i) , ans -= (last - i + 1) * query(n / i);
f[n] = ans;
return ans;
}
int main()
{
ll i , j , n;
phi[1] = sum[1] = 1;
for(i = 2 ; i <= m ; i ++ )
{
if(!np[i]) phi[i] = i - 1 , prime[++tot] = i;
for(j = 1 ; j <= tot && i * prime[j] <= m ; j ++ )
{
np[i * prime[j]] = 1;
if(i % prime[j] == 0)
{
phi[i * prime[j]] = phi[i] * prime[j];
break;
}
else phi[i * prime[j]] = phi[i] * (prime[j] - 1);
}
sum[i] = sum[i - 1] + phi[i];
}
scanf("%lld" , &n);
printf("%lld\n" , query(n));
return 0;
}


|转载请注明 [原文链接][作者] ，谢谢！

posted @ 2017-06-07 15:45  GXZlegend  阅读(534)  评论(0编辑  收藏  举报