Co-prime 杭電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.

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}. 
 題目大意:給你3個數A,B,C,讓你求出從A到B的全部數字中與C互質的個數,
題解:直接求互質很差求,咱們就求與C不互質的個數,而後最後在減去就能夠了
#include<iostream>
#include<cstdio>
#include<vector>
#include<cstring>
using namespace std;
typedef long long ll;
const int N=1E5+7;
ll arr[N];
vector<ll >ve;
int main(){
    int t,k=0;
    scanf("%d",&t);
    while(t--){
        k++;
        ll a,b,c,pos=0;
        scanf("%lld%lld%lld",&a,&b,&c);
        for(int i=2;i*i<=c;i++){
            if(c%i==0){
                pos++;
                ve.push_back(i);
                while(c%i==0) c/=i;
            }
        }
        if(c>1) 
        {
            pos++;
            ve.push_back(c);
        }
        ll sa=0,sb=0;
        for(ll i=1;i<(1<<pos);i++){
            ll sum=1,cnt=0;
            for(ll j=0;j<pos;j++){
                if(1&(i>>j)){
                    sum*=ve[j];
                    cnt++;
                }
            }
            if(cnt&1){//容斥裏的奇減偶加 
                sa+=(a-1)/sum;//a-1前有多少個數字是sum的倍數, 
                sb+=(b)/sum;
            }
            else {
                sa-=(a-1)/sum;
                sb-=(b)/sum;
            }
        }
        sb=sb-sa;//應題目要求  從A到B 
        printf("Case #%d: %lld\n",k,b-a+1-sb);
        ve.clear();
    }
    return 0;
} 
相關文章
相關標籤/搜索