C - Co-prime

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.

·······

这道题分几步:

1、先把n用算术基本原理拆分成不同的质数,如果a~b中的数是这些质数的倍数那其肯定不与n互质,a~b的总个数减去不与n互质的数剩下来就是与n互质的数啦

2、先计算1~a-1中与n互质的个数,再计算1~b中与n互质的个数,相减。

#include<iostream>
using namespace std;
typedef long long ll;
ll a[10000];
int main()
{
    ll t;
    cin>>t;
    for(ll ii=1;ii<=t;ii++)
    {
        ll x,y,n;
        cin>>x>>y>>n;
        ll num=1,sum=1,all=0,times;
        for(int i=2;i*i<=n;i++)   //向a数组里塞n的质因数
        {
             if(n%i==0)   
            {
                num++;
                a[num]=i;
            }
            while(n%i==0)
            {
                n=n/i;
            }
         } 
        if(n>1)  a[++num]=n;
        for(int i=1;i<(1<<num);i++)
        {
            times=0,sum=1;
            for(int j=0;j<num;j++)  //num个因数,乘了几个 
            {
                if(1&(i>>j))      //判断有没有选中第j个因数 
                {
                    sum*=a[j+1];
                    times++;
                }
            }
            if(sum==1||sum==0)
            continue; 
            if(times%2==1)
            {
                all+=y/sum;
                all-=(x-1)/sum;
            }
            else{
                all-=y/sum;
                all+=(x-1)/sum;
            }
        }
        printf("Case #%lld: %lld\n",ii,y-x+1-all);
    }
    return 0;
} 

以上。

猜你喜欢

转载自www.cnblogs.com/zjydeoneday/p/11361000.html