P2257 YY的GCD
第一次做的时候没有优化到底,T了
我竟然蠢蠢地去枚举质数了
#include <iostream> #include <cstdio> #include <queue> #include <algorithm> #include <cmath> #include <cstring> #define inf 2147483647 #define N 10000010 #define mod 1000000007 #define p(a) putchar(a) #define For(i,a,b) for(long long i=a;i<=b;++i) //by war //2020.8.6 using namespace std; long long T,n,m,cnt,ans; long long prime[N],mu[N]; bool vis[N]; void in(long long &x){ long long y=1;char c=getchar();x=0; while(c<'0'||c>'9'){if(c=='-')y=-1;c=getchar();} while(c<='9'&&c>='0'){ x=(x<<1)+(x<<3)+c-'0';c=getchar();} x*=y; } void o(long long x){ if(x<0){p('-');x=-x;} if(x>9)o(x/10); p(x%10+'0'); } void Euler(){ mu[1]=1; For(i,2,1e7){ if(!vis[i]) prime[++cnt]=i,mu[i]=-1; for(long long j=1;j<=cnt&&i*prime[j]<=1e7;j++){ vis[i*prime[j]]=1; if(i%prime[j]==0){ mu[i*prime[j]]=0; break; } mu[i*prime[j]]=-mu[i]; } } For(i,1,1e7) mu[i]+=mu[i-1]; } int solve(int n,int m){ int r=0; for(int i=1,j;i<=min(n,m);i=j+1){ j=min(n/(n/i),m/(m/i)); r+=(mu[j]-mu[i-1])*(n/i)*(m/i); } return r; } signed main(){ Euler(); in(T); while(T--){ in(n);in(m); ans=0; For(i,1,cnt){ if(prime[i]>n || prime[i]>m) break; ans+=solve(n/prime[i],m/prime[i]); } o(ans);p('\n'); } return 0; }
#include <iostream> #include <cstdio> #include <queue> #include <algorithm> #include <cmath> #include <cstring> #define inf 2147483647 #define N 10000010 #define mod 1000000007 #define p(a) putchar(a) #define For(i,a,b) for(register int i=a;i<=b;++i) //by war //2020.8.6 using namespace std; long long T,n,m,cnt,ans; int prime[N],mu[N],g[N]; bool vis[N]; inline void in(long long &x){ long long y=1;char c=getchar();x=0; while(c<'0'||c>'9'){if(c=='-')y=-1;c=getchar();} while(c<='9'&&c>='0'){ x=(x<<1)+(x<<3)+c-'0';c=getchar();} x*=y; } inline void o(long long x){ if(x<0){p('-');x=-x;} if(x>9)o(x/10); p(x%10+'0'); } inline void Euler(){ mu[1]=1; For(i,2,1e7){ if(!vis[i]) prime[++cnt]=i,mu[i]=-1; for(register int j=1;j<=cnt&&i*prime[j]<=1e7;j++){ vis[i*prime[j]]=1; if(i%prime[j]==0){ mu[i*prime[j]]=0; break; } mu[i*prime[j]]=-mu[i]; } } For(j,1,cnt) for(register int i=1;i*prime[j]<=1e7;i++){ g[i*prime[j]]+=mu[i]; } For(i,1,1e7) g[i]+=g[i-1]; } inline long long solve(long long n,long long m){ long long r=0; for(register int i=1,j;i<=n;i=j+1){ j=min(n/(n/i),m/(m/i)); r+=(n/i)*(m/i)*(g[j]-g[i-1]); } return r; } signed main(){ Euler(); in(T); while(T--){ in(n);in(m); if(n>m) swap(n,m); o(solve(n,m));p('\n'); } return 0; }