容斥做,欧拉好像比这个麻烦???
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<vector> 5 6 using namespace std; 7 typedef long long ll; 8 9 ll solve(ll a,ll n){ 10 vector<ll> v; 11 for(ll i = 2 ; i*i <= n ; i ++){ // 质数分解 12 if(n % i == 0){ 13 v.push_back(i); 14 while(n%i == 0) n/=i; 15 } 16 } 17 if(n > 1) v.push_back(n); 18 //有几位素因子 ,用二进制表示是否用过 19 ll sum = 0,tmp,cnt; 20 for(ll i = 1 ; i < (1<<v.size()) ; i ++){ 21 cnt = 0; 22 tmp = 1; 23 for(ll j = 0 ; j < v.size() ; j ++){ 24 if(i & (1<<j)){ 25 tmp *= v[j]; // 2 3; 6 12 18 26 cnt++; 27 } 28 } 29 if(cnt & 1) sum += a/tmp; //容斥 ,sum表示有1-a中有几个数字与n不互质 30 else sum -= a/tmp; 31 } 32 return a - sum; 33 } 34 35 int main(){ 36 int T; 37 scanf("%d",&T); 38 for(int cas = 1 ; cas <= T ; cas ++){ 39 ll a,b,n; 40 scanf("%lld%lld%lld",&a,&b,&n); 41 printf("Case #%d: %lld\n",cas,solve(b,n) - solve(a-1,n)); 42 } 43 return 0; 44 }
时间: 2024-10-29 19:09:48