转载网址: 点击打开链接
Co-prime
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 3495 Accepted Submission(s): 1381
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.
2 1 10 2 3 15 5
Case #1: 5 Case #2: 10HintIn the first test case, the five integers in range [1,10] which are relatively prime to 2 are {1,3,5,7,9}.
这道题确实应该好好的写一篇题解了。
如果是求小于 n 且与 n 互质的数的个数,可以用欧拉函数解决,但是这道题a,b的范围可能大于 k ,所以应该这么用容斥原理来做:
求 1~a-1 中与 k 互质的数,再求 1 ~ b 中与 k 互质的数,后者减去前者就是答案。
然后就是求 1 ~ n 中与 k 互质的数有多少,我们可以反着,先求 1 ~ n 中与 k 不互质的数有多少。
这点求法再拉出来细说:先把 k 分解质因数,存在一个数组中。
举个例子,比如 k 的质因子有 2,3,5。那么2、3、5的倍数都不和 k 互质,另外还没有完,可能有重复的地方,比如6,既是2的倍数又是3的倍数,前面用 k/2 + k/3 的时候多减了,这个时候要加上 k / (2*3)。同理,10,15这一类数都应该加上。但是还有类似于30这样的数,它是2,3,5的倍数,减的时候又多减了。
然后我们会发现,出现奇数个数,就用加法,偶数个数用减法。
最后的式子是这样的:k / 2 + k / 3 + k / 5 - k / (2 * 3) - k / (3 * 5) - k / (2 * 5) + k / (2 * 3 * 5)
有点长,看一下容易发现我说的奇偶的规律。
但是要怎么取算这个又出现问题了。
这里提供二进制的方法,个人觉得比较好理解。
设质因数的个数为m。
有一个浮动的数字,从1 ~ m依次递增,它的二进制的每一位表示用了哪些数字,比如5(101),其二进制的第一位和第三位(倒着数)是1,则它表示用了第一个质因数和第三个质因数。就是这个意思,这样就能发现:从1到m遍历一遍,就把所有的可能都包括了。
写的挺累的,有错误谢谢指正,转载说明出处。
下面看一下代码理解一下: