hdu Co-prime

本文介绍了一种算法,用于计算指定区间内与给定数N互质的整数个数。通过分解N的质因数并运用容斥原理,结合位运算实现了高效计算。

题意:求出在一个区间[A,B]内与N互质的个数 。

思路:

先求出n的质因子,然后求出与N的质因子不互质的个数然后总个数减去就是。用位运算二进制表示那个因子用到过,实现容斥原理。在1到n之间是c倍数的个数为n/c;

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <algorithm>
 4 #define LL __int64
 5 using namespace std;
 6 
 7 int t;
 8 LL a,b,n;
 9 LL f[1000];
10 int cnt;
11 
12 void inti()
13 {
14     memset(f,0,sizeof(f));
15     cnt=0;
16     for(int i=2; i*i<=n; i++)
17     {
18         if(n%i==0)
19         {
20            f[cnt++]=i;
21            while(n%i==0)
22            {
23                n=n/i;
24            }
25         }
26     }
27     if(n>1)
28     {
29         f[cnt++]=n;
30     }
31 }
32 
33 LL Get_num(LL m)
34 {
35     LL ans=0;
36     for(int i=1; i<(1<<cnt); i++)
37     {
38         int xx=0;
39         LL x=1;
40         for(int j=0; j<cnt; j++)
41         {
42             if(i&(1<<j))
43             {
44                xx++;
45                x*=f[j];
46             }
47         }
48         if(xx%2!=0)
49         {
50             ans+=m/x;
51         }
52         else
53         {
54             ans-=m/x;
55         }
56     }
57     return m-ans;
58 }
59 
60 int main()
61 {
62     scanf("%d",&t);
63     for(int cas=1; cas<=t; cas++)
64     {
65         scanf("%I64d%I64d%I64d",&a,&b,&n);
66         inti();
67         printf("Case #%d: %I64d\n",cas,Get_num(b)-Get_num(a-1));
68     }
69     return 0;
70 }
View Code

 

转载于:https://www.cnblogs.com/fanminghui/p/4106638.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值