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

Co-prime(容斥原理)

时间:2018-04-05 23:15:22      阅读:270      评论:0      收藏:0      [点我收藏+]

标签:iostream   time   source   c代码   body   orm   end   range   bottom   

Co-prime

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 6425    Accepted Submission(s): 2569


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
 

 

Recommend
lcy

 

 

AC代码:

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<vector>
 4 typedef long long ll;
 5 
 6 using namespace std;
 7 
 8 long long solve(long long n, long long r)
 9 {
10     vector<int> p;
11     p.clear();
12     for(ll i = 2; i * i <= n; i++)
13     {
14         if(n % i == 0)
15         {
16             p.push_back(i);
17             while(n % i == 0)
18             {
19                 n /= i;
20             }
21         }
22     }
23     if(n > 1)
24         p.push_back(n);
25     ll sum = 0;
26     for(ll msk = 1; msk < ((ll)1 << p.size()); msk++)
27     {
28         ll mult = 1, bits = 0;
29         for(ll i = 0; i < p.size(); i++)
30         {
31             if(msk & ((ll)1 << i))
32             {
33                 bits++;
34                 mult *= p[i];
35             }
36         }
37         ll cur = r / mult;
38         if(bits % 2 == 1)
39             sum += cur;
40         else
41             sum -= cur;
42     }
43     return r-sum;
44 }
45 
46 int main()
47 {
48     int t;
49     long long a, b, n;
50     scanf("%d", &t);
51     int cas = 1;
52     while(t--)
53     {
54         scanf("%lld %lld %lld", &a, &b, &n);
55         long long f1 = solve(n, b);
56         long long f2 = solve(n, a-1);
57         printf("Case #%d: %lld\n", cas++, f1 - f2);
58     }
59     return 0;
60 }

 

Co-prime(容斥原理)

标签:iostream   time   source   c代码   body   orm   end   range   bottom   

原文地址:https://www.cnblogs.com/ruruozhenhao/p/8724578.html

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