数学: HDU Co-prime

Co-prime

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 32768/32768K (Java/Other)
Total Submission(s) : 12   Accepted Submission(s) : 4

Font: Times New Roman | Verdana | Georgia

Font Size:  

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

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

Source

The Third Lebanese Collegiate Programming Contest

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include<iostream>
#include<cstring>
#include<cstdio>
  
using namespace std;
typedef long long LL;
const int N = 1e5+5;
  
LL f[N],prime[N],vis[N],cnt,k;
void prime_factor(){
    memset(vis,0,sizeof(vis));
    vis[0]=vis[1] = 1,cnt = 0;
    for(LL i=2;i*i<N;i++)
    if(!vis[i]) for(LL j=i*i;j<N;j+=i) vis[j] = 1;
    for(LL i=0;i<N;i++) if(!vis[i]) prime[cnt++] = i;
}
LL poie(LL x){
    LL ret = 0,sum,tmp;
    for(LL i=1;i<(1LL<<k);i++){
        tmp = 1,sum=0;
        for(LL j=0;j<k;j++) if(i&(1LL<<j)){sum++,tmp*=f[j];}
        if(sum&1) ret += x/tmp;
        else ret -= x/tmp;
    }
    return ret;
}
  
void solve_question(LL A,LL B,LL n){
    LL tmp = n;
    k = 0 ;
    for(LL i=0;prime[i]*prime[i]<= tmp;i++){
        if(tmp%prime[i]==0)
            f[k++] = prime[i];
        while(tmp%prime[i]==0)
            tmp/=prime[i];
    }
    if(tmp > 1) f[k++] = tmp;
    LL ans =B-poie(B)-A+1+poie(A-1);
    printf("%I64d ",ans);
}
int main(){
    int T,Case=0;
    LL A,B,n;
    scanf("%d",&T);
    prime_factor();
    while(T--){
        scanf("%I64d %I64d %I64d",&A,&B,&n);
        printf("Case #%d: ",++Case);
        solve_question(A,B,n);
    }
}
 
原文地址:https://www.cnblogs.com/Pretty9/p/7347696.html