Python 二进制表示中设置位的质数
pythonserver side programmingprogramming更新于 2025/7/8 18:52:17
假设我们有两个整数 L 和 R,我们必须找到在 [L, R](含)范围内具有质数设置位的二进制数字的数量。
因此,如果输入为 L = 6 和 R = 10,则输出将为 4,因为有 4 个数字 6(110)、7(111)、9(1001)、10(1010),所有数字都具有质数设置位。
为了解决这个问题,我们将遵循以下步骤 −
- count := 0
- 对于 L 到 R 范围内的 j,执行
- 如果 j 的设置位数在 [2,3,5,7,11,13,17,19] 中,则
- count := count + 1
- 返回 count
让我们看看下面的实现以便更好地理解 −
示例
class Solution:
def countPrimeSetBits(self, L, R):
def popcount(i):
return bin(i)[2:].count('1')
count = 0
for j in range(L,R+1):
if popcount(j) in [2,3,5,7,11,13,17,19]:
count +=1
return count
ob = Solution()
print(ob.countPrimeSetBits(6,10))
输入
6,10
输出
4
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

