Co-prime
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Problem Description
Given a number N, you are asked to count the number of integers between A and B inclusive which are relatively prime to N.
Two integers are said to be co-prime or relatively prime if they have no common positive divisors other than 1 or, equivalently, if their greatest common divisor is 1. The number 1 is relatively prime to every integer.
Two integers are said to be co-prime or relatively prime if they have no common positive divisors other than 1 or, equivalently, if their greatest common divisor is 1. The number 1 is relatively prime to every integer.
Input
The 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 <= 1015) and (1 <=N <= 109).
Output
For 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 Input
2
1 10 2
3 15 5
Sample Output
Case #1: 5
Case #2: 10
Hint
In the first test case, the five integers in range [1,10] which are relatively prime to 2 are {1,3,5,7,9}. Source
题意:给你三个数,求[A,B]区间内与N互质的数的个数;
思路:即求[1,B]-[1,A-1]内与N互质的数
因为n为1e9,所以根号打表,将N唯一分解,
容斥得到与N不互质的数的个数;
ans=B-[1,B]-(A-1-[1,A-1]);

#include<iostream> #include<cstdio> #include<cmath> #include<string> #include<queue> #include<algorithm> #include<stack> #include<cstring> #include<vector> #include<list> #include<set> #include<map> using namespace std; #define ll __int64 #define mod 1000000007 #define inf 999999999 //#pragma comment(linker, "/STACK:102400000,102400000") int scan() { int res = 0 , ch ; while( !( ( ch = getchar() ) >= '0' && ch <= '9' ) ) { if( ch == EOF ) return 1 << 30 ; } res = ch - '0' ; while( ( ch = getchar() ) >= '0' && ch <= '9' ) res = res * 10 + ( ch - '0' ) ; return res ; } ll prime[100010]; ll vis[100010]; ll a[110]; ll ji,cnt; ll ans,x,y,z; ll gcd(ll x,ll y) { return y==0?x:gcd(y,x%y); } void Prime(ll n) { cnt=0; memset(vis,0,sizeof(vis)); for(ll i=2;i<n;i++) { if(!vis[i]) prime[cnt++]=i; for(ll j=0;j<cnt&&i*prime[j]<n;j++) { vis[i*prime[j]]=1; if(i%prime[j]==0)//关键 break; } } } void dfs(ll lcm,ll pos,ll step,ll x,ll &ans) { if(lcm>x) return; if(pos==ji) { if(step==0) return; if(step&1) ans+=(x/lcm); else ans-=(x/lcm); return; } dfs(lcm,pos+1,step,x,ans); dfs(lcm/gcd(a[pos],lcm)*a[pos],pos+1,step+1,x,ans); } int main() { ll t,i; int cs=1; Prime(100000); scanf("%I64d",&t); while(t--) { ji=0; scanf("%I64d%I64d%I64d",&x,&y,&z); for(i=0;i<cnt;i++) if(z%prime[i]==0) { a[ji++]=prime[i]; while(z%prime[i]==0) z/=prime[i]; } if(z>1) a[ji++]=z; ll gg=0; ans=0; dfs(1,0,0,x-1,gg); dfs(1,0,0,y,ans); printf("Case #%d: ",cs++); printf("%I64d ",(y-ans)-(x-1-gg)); } return 0; }