HDOJ 4135 Co-prime (容斥原理)
2015-11-11 20:14
274 查看
Co-prime
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2751 Accepted Submission(s): 1055
[align=left]Problem Description[/align]
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.
[align=left]Input[/align]
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).
[align=left]Output[/align]
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.
[align=left]Sample Input[/align]
2
1 10 2
3 15 5
[align=left]Sample Output[/align]
Case #1: 5
Case #2: 10
HintIn 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互质的数的个数
思路:这个题一看就会想到欧拉函数,但是稍微一想就会发现,eular(A)-eular(B)是不可行的,因为会有重复项出现,所以就想到了容斥原理
先求出1-A中与N不互斥的数,然后用A减一下就得到了和N互斥的数的个数。例如:A=12,N =30,
那么:求出N的质因子为:2,3,5,
容斥原理公式:ans=N/2+N/3+N/5-N/(2*3)-N/(2*5)-N/(3*5)+N/(2*3*5)。
用队列数组法实现容斥原理:
que数组保存分母的大小,开始时数组没有数,然后给其赋值,k为质因子的数目,所以最高的que也就是k个质因子相乘,在遍历第i个质因子的时候
对之前的que数组进行累乘,例如:que[1]=2,que[2]=3,que[3]=2*3,que[4]=5,que[5]=2*5,que[6]=3*5,que[7]=2*3*5, 在这个过程中对其进行变号确定其正
负,最后遍历用num相处然后累加就行了。
ac代码:
#include<stdio.h> #include<string.h> #include<math.h> #include<iostream> #include<algorithm> #define fab(a) (a)>0?(a):(-a) #define LL long long #define MAXN 10010 #define INF 0xfffffff using namespace std; LL aprime[MAXN]; LL k; void findprime(LL x)//求一个数的质因子 { k=0; for(LL i=2;i*i<=x;i++) { if(x%i==0) { aprime[k++]=i; while(x%i==0) x/=i; } } if(x>1)//不可少 aprime[k++]=x; } LL fun(LL num)//队列法实现容斥原理 { LL que[MAXN],i,j,kk,ans=0,t=0; que[t++]=-1; for(i=0;i<k;i++) { kk=t; for(j=0;j<kk;j++) que[t++]=aprime[i]*que[j]*(-1); } for(i=1;i<t;i++) ans+=(num/que[i]); return ans; } int main() { int t; int cas=0; LL a,b,n; scanf("%d",&t); while(t--) { scanf("%lld%lld%lld",&a,&b,&n); findprime(n); LL ans=(b-fun(b))-(a-1-fun(a-1)); printf("Case #%d: %lld\n",++cas,ans); } return 0; }
相关文章推荐
- 图片列表换行错位,图片无法左对齐怎么办
- Unity加载进度条
- opencv笔记 2.一些简单的绘图函数使用
- 基于opencv的相机之图像修补功能实现(十二)
- 使用 getprop 命令查看 android 系统允许进程分配的内存大小
- orcl
- 【SDCC讲师专访】腾讯潘安群:腾讯云金融级数据库TDSQL分析
- java定时器初探
- 基于opencv的相机之鬼怪贴图功能实现(十一)
- C# Socket简单例子(服务器与客户端通信)
- 黑马程序员——String类
- java基础内存分析
- JAVA中File类遍历目录解析
- 国产低价手机低的是“专利” 谈何技术创新?
- maven使用指南
- MyEclipse安装插件
- TR111 and TR069 function development note (1)
- 第10章 多环境下构建项目
- 第10章 多环境下构建项目
- maven使用指南