码迷,mamicode.com
首页 > 其他好文 > 详细

C - Co-prime

时间:2019-08-15 22:45:15      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:ios   class   space   选中   you   没有   ati   case   tween   

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;
} 

以上。

 

C - Co-prime

标签:ios   class   space   选中   you   没有   ati   case   tween   

原文地址:https://www.cnblogs.com/zjydeoneday/p/11361000.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!