码迷,mamicode.com
首页 > 其他好文 > 详细

(LeetCode)Count Primes --- 统计素数(质数)

时间:2016-08-19 11:24:54      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

Description:

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

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

Hint:

  1. 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 isPrimefunction would be O(n) and hence counting the total prime numbers up to n would be O(n2). Could we do better


解题分析:
为了寻求最小的时间复杂度,这里使用埃拉斯特尼筛选法,
学习链接:
http://blog.csdn.net/u012965373/article/details/52248039
# -*- coding:utf-8 -*-
__author__ = 'jiuzhang'
class Solution(object):
    def countPrimes(self, n):
        isPrime = [True] * max(n, 2)
        isPrime[0], isPrime[1] = False, False
        x = 2
        while x * x < n:
            if isPrime[x]:
                p = x * x
                while p < n:
                    isPrime[p] = False
                    p += x
            x += 1
        return sum(isPrime)






(LeetCode)Count Primes --- 统计素数(质数)

标签:

原文地址:http://blog.csdn.net/u012965373/article/details/52248447

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!