D - It’s a Mod, Mod, Mod, Mod World
化简
∑
i
=
1
n
⌊
(
p
∗
i
m
o
d
q
)
⌋
\sum_{i=1}^{n} {\lfloor(p*i\mod q)\rfloor}
∑i=1n⌊(p∗imodq)⌋=
∑
i
=
1
n
p
∗
i
−
⌊
p
∗
i
q
⌋
\sum_{i=1}^{n}p*i- {\lfloor\frac {p*i} {q}\rfloor}
∑i=1np∗i−⌊qp∗i⌋*q=
(
n
+
1
)
n
2
\frac {(n+1)n} {2}
2(n+1)n*p-q
∑
i
=
1
n
⌊
p
∗
i
q
⌋
\sum_{i=1}^{n}{\lfloor\frac {p*i} {q}\rfloor}
∑i=1n⌊qp∗i⌋
后面那部分式子就可以用类欧几里德来计算。
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <map>
using namespace std;
typedef long long ll;
ll lexgcd(ll a,ll b,ll c,ll n)
{
if(!a)
{
return (n+1)*(b/c);
}
if(a>=c||b>=c)
{
return (n*(n+1)/2*(a/c))+(n+1)*(b/c)+lexgcd(a%c,b%c,c,n);
}
int m=(a*n+b)/c;
return n*m-lexgcd(c,c-b-1,a,m-1);
}
int main()
{
int t;
cin>>t;
while(t--)
{
ll p,q,n;
cin>>p>>q>>n;
ll ans=0;
ans=(n+1)*n/2*p-q*lexgcd(p,0,q,n);
cout<<ans<<endl;
}
return 0;
}