用 Python 统计质数


假设我们有一个上限 n。我们必须统计在范围 2 到 n 中出现的质数数量。因此,如果 n = 10,结果将为 4。因为在 10 之前有四个质数,它们是 2、3、5、7。

为解决此问题,我们将遵循以下方法 −

  • count = 0
  • 创建一个大小为 n + 1 的数组 prime =,并用 False 填充它
  • 对于 i = 0 到 n,执行
    • 如果 prime[i] = 假,则
      • count 增加 1
      • 设置 j = 2
      • 当 j * i <n 时,则
        • prime[i * j] = True
        • j = j + 1
  • 返回 count

示例

让我们看看以下实现以更好地理解 −

 在线演示

class Solution(object):
   def countPrimes(self, n):
      """
      :type n: int
      :rtype: int
      """
      count = 0
      primes = [False for i in range(n+1)]
      for i in range(2,n):
         if primes[i] == False:
            count+=1
            j = 2
            while j*i<n:
               primes[j*i] = True
               j+=1
      return count
ob1 = Solution()
print(ob1.countPrimes(50))
print(ob1.countPrimes(10))

输入

n = 50
n = 10

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

输出

15
4

更新于: 28-4 月-2020

4K+ 次观看

开启你的职业

完成该课程以获得认证

开始学习
广告