Co-prime//HDU - 4135//数论
题目
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.
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 <= 10 15) and (1 <=N <= 10 9).
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
题意
a与b之间与n互质的数有多少
链接:https://vjudge.net/contest/351853#problem/K
思路
列出n的因数,排列组合成各个因子,利用容斥原理,奇数个因子组成的为加,偶数为减
代码
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
using namespace std;
typedef long long ll;
ll x[1100000],a[1100000];
ll cnt;
void put(ll n){ //分解质因数
cnt=0;
for(ll i=2;i*i<=n;i++){
if(n%i==0){
while(n%i==0)
n/=i;
x[cnt++]=i;
}
}
if(n!=1)
x[cnt++]=n;
}
ll solve(ll n){ //利用容斥原理奇减偶加
ll cnt2=0,temp,ans=0;
a[cnt2++]=-1;
for(ll i=0;i<cnt;i++){
temp=cnt2;
for(ll j=0;j<temp;j++){ //利用质因数组成各个因数
a[cnt2++]=-1*a[j]*x[i];
}
}
for(ll i=1;i<cnt2;i++){
ans+=n/a[i];
}
//printf("%lld\n",ans);
return ans;
}
int main()
{
ll t,casen=1;
scanf("%lld",&t);
while(t--){
ll a,b,n;
scanf("%lld%lld%lld",&a,&b,&n);
put(n);
ll ans=b-solve(b)-(a-1-solve(a-1));
printf("Case #%lld: %lld\n",casen++,ans);
}
return 0;
}
注意
把因子加上正负方便最后判断是加还是减