前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >HDU 4135 Co-prime(容斥原理)

HDU 4135 Co-prime(容斥原理)

作者头像
ShenduCC
发布2018-04-26 17:16:02
6210
发布2018-04-26 17:16:02
举报
文章被收录于专栏:算法修养

Co-prime

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 3313    Accepted Submission(s): 1286

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.

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

代码语言:javascript
复制
2
1 10 2
3 15 5

Sample Output

代码语言:javascript
复制
Case #1: 5
Case #2: 10
求在n在a~b之间的和n互质的个数
容斥原理模板题#include <iostream>
#include <string.h>
#include <algorithm>
#include <stdlib.h>
#include <math.h>
#include <stdio.h>

using namespace std;
typedef long long int LL;
const LL INF=(LL)1<<62;
#define MAX 1000000
LL prime[MAX+5];
LL sprime[MAX+5];
LL q[MAX+5];
bool check[MAX+5];
LL n,a,b,cnt;
void eular()
{
    memset(check,false,sizeof(check));
    int tot=0;
    for(LL i=2;i<MAX+5;i++)
    {
        if(!check[i])
            prime[tot++]=i;
        for(int j=0;j<tot;j++)
        {
            if(i*prime[j]>MAX+5) break;
             check[i*prime[j]]=true;
            if(i%prime[j]==0) break;
        }
    }
}
void Divide(LL n)
{
    cnt=0;
    LL t=(LL)sqrt(1.0*n);
    for(LL i=0;prime[i]<=t;i++)
    {
        if(n%prime[i]==0)
        {
            sprime[cnt++]=prime[i];
            while(n%prime[i]==0)
                n/=prime[i];
        }
    }
    if(n>1)
        sprime[cnt++]=n;
}
LL Ex(LL n)
{
    LL sum=0,t=1;
    q[0]=-1;
    for(LL i=0;i<cnt;i++)
    {
        LL x=t;
        for(LL j=0;j<x;j++)
        {
            q[t]=q[j]*sprime[i]*(-1);
            t++;
        }
    }
    for(LL i=1;i<t;i++)
        sum+=n/q[i];
    return sum;
}
int main()
{
    int t;
    scanf("%d",&t);
    eular();
    int cas=0;
    while(t--)
    {
        scanf("%lld%lld%lld",&a,&b,&n);
        Divide(n);
        printf("Case #%d: %lld\n",++cas,(b-Ex(b)-(a-1-Ex(a-1))));
    }
    return 0;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016-05-04 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Co-prime
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档