HDU4135 Co-prime【容斥原理】3方法

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 <= 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

Hint

In the first test case, the five integers in range [1,10] which are relatively prime to 2 are {1,3,5,7,9}.
题意:计算从a到b中与n的共同因子只有1的数字个数。
思路:欧拉函数肯定在这里是无法应用的,这里应用了容斥原理, HDU4135 Co-prime【容斥原理】3方法_第1张图片
HDU4135 Co-prime【容斥原理】3方法_第2张图片
如上图为容斥原理的思路:
1.位运算遇到集合是奇数的就加,偶数的就减
2.队列数组
3.递归算法
分析:
n和1——a-1的不互素个数num1, 互素个数a-1-num1
n和1——b的不互素个数num2,互素个数b-num2
最后结果为b-num2-(a-1-num1)
1.位运算:(素因子的个数全局变量cnt记录)
#include 
#include 
#include 
#include 
using namespace std;
typedef long long ll;
ll prime[100];
int cnt;
void init(int m)
{
     cnt=0;
    for(ll i=2;i*i1)
        prime[cnt++]=m;//这里是因为有的n的因子大于sqrt(n),比如14,他的素因子有2,7,
}
ll rong_chi(ll cur)
{
    ll res,ans=0;
    for(ll i=1;i>t;
    int icase=0;
    while(t--){
        memset(prime,0,sizeof(prime));
        ll a,b,n;
        int len=0;
        cin>>a>>b>>n;
        init(n);

        printf("Case #%d: %lld\n",++icase,b-rong_chi(b)-(a-1-rong_chi(a-1)));
    }
    return 0;
}


2.队列数组(素因子个数用全局变量cnt记录)
#include 
#include 
#include 
using namespace std;
typedef long long ll;
int prime[50],cnt;
int sum[1<<11],q;
void init(int m)
{
     cnt=0;
    for(ll i=2;i*i1)
        prime[cnt++]=m;//这里是因为有的n的因子大于sqrt(n),比如14,他的素因子有2,7,
}
ll que[100005];
ll solve(ll m)
{
    ll k,front=0,sum=0;
    que[front++]=-1;
    for(ll i=0;i


3.递归(素因子的个数记录在全局变量cnt)
#include
#include
#include
using namespace std;
typedef long long ll;
int prime[20],cnt;
void Init(int m)
{
    int i;
    cnt=0;
    for(i=2;i*i<=m;i++)
        if(m%i==0){
        	prime[cnt++]=i;
        	while(m%i==0)	m/=i;
        }
    if(m!=1)	prime[cnt++]=m;

}
ll Noprime(int m,ll n,int x)
{
    ll i,ret=0;
    for(i=x;i
以上三分代码的容斥原理的部分都可以当做容斥原理的模板



你可能感兴趣的:(ACM_数字处理与数论)