InputThe first line on input contains T (0 < T <= 100) the number of test cases, each of the next T lines contains three integers A, B, N where (1 <= A <= B <= 10 15) and (1 <=N <= 10 9).OutputFor each test case, print the number of integers between A and B inclusive which are relatively prime to N. Follow the output format below.Sample Inputios
2 1 10 2 3 15 5
Sample Outputui
Case #1: 5 Case #2: 10
Hintspa
In the first test case, the five integers in range [1,10] which are relatively prime to 2 are {1,3,5,7,9}.
首先分解質因子,而後利用容斥原理分別求出0—(A-1 )的不互質個數和0—(B)的不互質個數,答案可求。
#include<iostream> #include<cstdio> #include<cstring> using namespace std; #define LL long long #define maxn 70 LL p[maxn]; LL make_ans(LL num,int m)//1到num中的全部數與m個質因子不互質的個數 注意是不互質哦 { LL ans=0,tmp,i,j,flag; for(i=1;i<(LL)(1<<m);i++) { //用二進制來1,0來表示第幾個素因子是否被用到,如m=3,三個因子是2,3,5,則i=3時二進制是011,表示第二、3個因子被用到 tmp=1,flag=0; for(j=0;j<m;j++) if(i&((LL)(1<<j)))//判斷第幾個因子目前被用到 flag++,tmp*=p[j]; if(flag&1)//容斥原理,奇加偶減 ans+=num/tmp; else ans-=num/tmp; } return ans; } int main() { int T,t=0,m; LL n,a,b,i; scanf("%d",&T); while(T--) { scanf("%lld%lld%lld",&a,&b,&n); m=0; for(i=2;i*i<=n;i++) //對n進行素因子分解 if(n&&n%i==0) { p[m++]=i; while(n%i==0) n/=i; } if(n!=1) p[m++]=n; printf("Case #%d: %I64d\n",++t,(b-make_ans(b,m))-(a-1-make_ans(a-1,m))); } return 0; }