Given N and M, calculate Σ (1 <= I <= N) Σ (1 <= j <= m) gcd (I, j) * 2-1
The limitation of I and j is different. The traditional linear screening method fails. Here we consider the principle of rejection.
Make f [x] The number of (I, j) pairs of gcd (I, j) = x.
We make G [x] The number of (I, j) pairs with a public factor = x (note that it is not the maximum public factor !), Obviously G [x] = (N/x) * (M/X)
But some of these number pairs have the largest public factor of 2D, 3D, and 4d. We need to remove them.
Then f [x] = (N/x) * (M/X)-Σ (2 * x <= I * x <= min (m, n )) f [I * x]
Enumerate X from the back to the front.
Time complexity O (nlogn)
Note that when G [x] is calculated (N/x) * (M/X), a point may crash.
#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>using namespace std;typedef long long ll;int m,n,k;ll f[100100],ans;int main(){int i,j;cin>>m>>n;k=min(m,n);for(i=k;i;i--){f[i]=(ll)(m/i)*(n/i);for(j=2;j*i<=k;j++)f[i]-=f[i*j];ans+=f[i]*(i+i-1);}cout<<ans<<endl;return 0;}
Bzoj 2005 noi2010 Number Theory