http://www.51nod.com/Challenge/Problem.html#!#problemId=1239
AC代码
#include <bits/stdc++.h> #define pb push_back #define mp make_pair #define fi first #define se second #define all(a) (a).begin(), (a).end() #define fillchar(a, x) memset(a, x, sizeof(a)) #define huan printf("\n"); #define debug(a,b) cout<<a<<" "<<b<<" "; using namespace std; const int maxn=1e6+10,inf=0x3f3f3f3f; typedef long long ll; const ll mod = 1000000007; typedef pair<int,int> pii; int check[maxn],prime[maxn],phi[maxn],sum[maxn]; void Phi(int N)//莫比乌斯函数线性筛 { int pos=0;sum[1]=phi[1]=1; for(int i = 2 ; i <= N ; i++) { if (!check[i]) prime[pos++] = i,phi[i]=i-1; for (int j = 0 ; j < pos && i*prime[j] <= N ; j++) { check[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])%mod; } } unordered_map<ll,ll> ma; ll inv2=500000004; ll solve(ll n) { if(n<=1e6) return sum[n]; else if(ma.count(n)) return ma[n]; ll temp = ((n%mod)*((n+1)%mod)%mod)*inv2%mod; for(ll i=2,j;i<=n;i=j+1) { j=n/(n/i); temp = (temp-solve(n/i)*(j-i+1)%mod+mod)%mod; } return ma[n]=temp; } int main() { ll n; Phi(1e6); scanf("%lld",&n); printf("%lld\n",solve(n)); }