题目链接:点击这里
解题思路:
首先要将原有的递推公式变成a[n] = n*n+n,那么前n项和就可以分为求n^2和n的前n项和,这个就有了很清楚了的公式了.然后就是将m质因子分解出来,用容斥求出和m不互质的数的贡献和。
#include<bits/stdc++.h>
#define fi first
#define se second
using namespace std;
typedef long long ll;
const int mx = 1e5 + 10;
const int mod = 1e9 + 7;
const int inv = 166666668;
const int fx[4] = {1,0,0,-1};
const int fy[4] = {0,1,-1,0};
int cnt[mx],top;
ll n,m,ans;
int a[mx];
void dfs1(int x,int d,ll v)
{
ll ret;
for(int i=x+1;i<top;i++){
ret = v*cnt[i];
if(ret>n) break;
ll k = n/ret;
if((d+1)&1) ans = (ans-ret*ret%mod*k%mod*(k+1)%mod*(2*k+1)%mod*inv%mod)%mod;
else ans = (ans+ret*ret%mod*k%mod*(k+1)%mod*(2*k+1)%mod*inv%mod)%mod;
dfs1(i,d+1,ret);
}
}
void dfs2(int x,int d,ll v)
{
ll ret;
for(int i=x+1;i<top;i++){
ret = v*cnt[i];
if(ret>n) break;
ll k = n/ret;
if((d+1)&1) ans = (ans-(k*(k+1))/2%mod*ret%mod)%mod;
else ans = (ans+(k*(k+1))/2%mod*ret%mod)%mod;
dfs2(i,d+1,ret);
}
}
int main()
{
while(~scanf("%lld%lld",&n,&m))
{
ans = top = 0;
for(int i=2;i*i<=m;i++){
if(m%i==0) cnt[top++] = i;
while(m%i==0) m/=i;
}
if(m!=1) cnt[top++] = m;
//ll ret = n*(n+1)%mod*(n+2)%mod*333333336%mod;
//cout << ret << endl;
ans = n*(n+1)%mod*(2*n+1)%mod*inv%mod;
ans = (ans+n*(n+1)/2%mod)%mod;
dfs1(-1,0,1);
dfs2(-1,0,1);
ans %= mod;
printf("%lld\n",(ans+mod)%mod);
}
return 0;
}