• LeetCode#204 Count Prime


    Problem Definition:

      Count the number of prime numbers less than a non-negative number, n.

    Hint:

      Let's start with a isPrime function. To determine if a number is prime, we need to check if it is not divisible by any number less than n.

      The runtime complexity of isPrime function would be O(n) and hence counting the total prime numbers up to n would be O(n2). Could we do better?

    Solution: (筛选法)

       1.  use square root of n.
         2.  use non-prime numbers as the step
         3.  use i*i as the start.
         4.  use count-- in every loop, avoiding another traversal.

     1 def countPrime(n):
     2     if n<=2:
     3         return 0
     4     if n==3:
     5         return 1
     6     prime=[True]*n
     7     count=n-2
     8     rt=sqrt(n)
     9     for i in range(2,rt+1):
    10         if prime[i]==True:
    11             for j in xrange(i*i,n,i):
    12                 if prime[j]==True:
    13                     prime[j]=False
    14                     count-=1
    15     return count
  • 相关阅读:
    HDU 3466(01背包变种
    HDU 2639(01背包第K大)
    POJ 2184(01背包)(负体积)
    UVA 562(01背包)
    UVA 624(01背包记录路径)
    SQL总结二
    oracle--知识点汇总1
    时间日期----java
    字符串、数值----转换
    字符串反转----示例
  • 原文地址:https://www.cnblogs.com/acetseng/p/4654211.html
Copyright © 2020-2023  润新知