A sequence of integer
{
a
n
}
\left \{ a_{n} \right \}
{an}can be expressed as:
a
n
=
{
0
n
=
0
2
n
=
1
3
a
n
−
1
−
a
n
−
2
2
+
n
+
1
n
>
1
a_{n}=\left\{\begin{matrix} 0&n=0 \\ 2&n=1 \\ \frac{3a_{n-1}-a_{n-2}}{2}+n+1&n>1 \end{matrix}\right.
an=⎩⎨⎧0223an−1−an−2+n+1n=0n=1n>1
Now there are two integers nn and mm. I’m a pretty girl. I want to find all
b
1
,
b
2
,
b
3
⋯
b
p
b_1,b_2,b_3\cdots b_p
b1,b2,b3⋯bpthat
1
⩽
b
i
⩽
n
1\leqslant b_i\leqslant n
1⩽bi⩽n is relatively-prime with the integer
m
m
m. And then calculate:
∑
i
=
1
p
a
b
i
\sum_{i=1}^pa_{b_i}
i=1∑pabi
But I have no time to solve this problem because I am going to date my boyfriend soon. So can you help me?
Input
Input contains multiple test cases ( about 15000 ). Each case contains two integers n and m.
1
≤
n
,
m
≤
1
0
8
1\leq n,m \leq 10^8
1≤n,m≤108
.
Output
For each test case, print the answer of my question(after mod 1,000,000,007).
Hint
In the all integers from 1 to 4, 1 and 3 is relatively-prime with the integer 4. So the answer is a_1+a_3=14
样例输入 复制
4 4
样例输出 复制
14
题意
已知 a i a_i ai序列,给你一个n和m求小于n与m互质的数作为a序列的下标的和
思路
我们通过打表发现
a
i
a_i
ai序列就等于
a
i
=
i
(
i
+
1
)
a_i=i(i+1)
ai=i(i+1),那么原问题就可以转换为求解
∑
i
=
1
n
i
(
i
+
1
)
[
g
c
d
(
i
,
m
)
=
=
1
]
\sum_{i=1}^ni(i+1)[gcd(i,m)==1]
i=1∑ni(i+1)[gcd(i,m)==1]
那我们可以考虑
[
1
,
n
]
[1,n]
[1,n]中与m有相同因子的数
∑
i
=
1
n
i
(
i
+
1
)
−
∑
d
∣
n
,
d
∣
m
d
(
d
+
1
)
\sum_{i=1}^ni(i+1)-\sum_{d|n,d|m}d(d+1)
i=1∑ni(i+1)−d∣n,d∣m∑d(d+1)
又有
i
(
i
+
1
)
=
i
2
+
i
i(i+1)=i^2+i
i(i+1)=i2+i
∑
i
=
1
n
i
2
+
i
=
n
(
n
+
1
)
(
2
n
+
1
)
6
+
n
(
n
+
1
)
2
\sum_{i=1}^ni^2+i=\frac{n(n+1)(2n+1)}{6}+\frac{n(n+1)}{2}
i=1∑ni2+i=6n(n+1)(2n+1)+2n(n+1)
我们要是枚举m的素因子,那么我们可以通过容斥找出
[
1
,
n
]
[1,n]
[1,n]中与m不互质的数,例如m的因子中含有2,那么
2
,
4
,
6
,
8
,
10
⋯
2,4,6,8,10\cdots
2,4,6,8,10⋯都是与m不互质的数,这些数的和我们可以提出一个2,然后数的长度就是
n
2
\frac{n}{2}
2n,然后套用上面的求和公式即可,然后对不同的因子的贡献再套用容斥模板即可,记得求和公式要用逆元
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <math.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
const long long mod=1e9+7;
long long a[10005];
long long inv6=166666668;
long long inv2=500000004;
long long clac(long long n,long long i)
{
n=n/i;
return (n%mod*(n+1)%mod*(2*n+1)%mod*inv6%mod*i%mod*i%mod+n%mod*(n+1)%mod*inv2%mod*i%mod)%mod;
}
int main()
{
long long n,m;
while(scanf("%lld%lld",&n,&m)!=EOF)
{
int cnt=0;
for(int i=2;i*i<=m;i++)
if(m%i==0)
{
a[cnt++]=i;
while(m%i==0)
m/=i;
}
if(m!=1)
a[cnt++]=m;
long long ans=clac(n,1);
long long ans2=0;
for(int i=1;i<(1<<cnt);i++)
{
int flag=0;
long long temp=1;
for(int j=0;j<cnt;j++)
if(i&(1<<j))
{
flag++;
temp=temp*a[j]%mod;
}
temp=clac(n,temp);
if(flag%2==1)
{
ans2=(ans2%mod+temp%mod)%mod;
}
else
ans2=(ans2%mod-temp%mod+mod)%mod;
}
printf("%lld\n",(ans%mod-ans2%mod+mod)%mod);
}
return 0;
}