[leetcode] 204. Count Primes 統計小於非負整數n的素數的個數

題目大意

https://leetcode.com/problems/count-primes/description/html

204. Count Primesweb

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

Example:測試

Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.spa

 

題目大意:
統計小於非負整數n的素數的個數code

提示:n的範圍是100,000到5,000,000htm

 

解題思路

參考文獻:blog

一共有多少個素數?(https://primes.utm.edu/howmany.html)ip

埃拉託斯特尼篩法 (http://en.wikipedia.org/wiki/Sieve_of_Eratostheneshttp://open.163.com/movie/2012/10/0/6/M99VJKUHC_M9ENDUB06.htmlleetcode

Sieve of Eratosthenes: algorithm steps for primes below 121 (including optimization of starting from prime's square).

 

僞代碼

Input: an integer n > 1. Let A be an array of Boolean values, indexed by integers 2 to n, initially all set to true. for i = 2, 3, 4, ..., not exceeding √n: if A[i] is true: for j = i2, i2+i, i2+2i, i2+3i, ..., not exceeding n: A[j] := false. Output: all i such that A[i] is true.

  

Python解法

起初Python的時間限制過於嚴格,採用Python解題對於測試樣例5000000老是返回Time Limit Exceeded,後來管理員放寬了Python的時限。

class Solution(object): def countPrimes(self, n): """ :type n: int :rtype: int """ is_prime = [True] * max(n, 2) is_prime[0], is_prime[1] = False, False x = 2
        while x * x < n: if is_prime[x]: p = x * x while p < n: is_prime[p] = False p += x x += 1
        return sum(is_prime) def countPrimes_v0(self, n): """ :type n: int :rtype: int """ is_prime = [True] * max(n, 2) is_prime[0], is_prime[1] = False, False for x in range(2, int(n ** 0.5) + 1): if is_prime[x]: p = x * x while p < n: is_prime[p] = False p += x return sum(is_prime)

 

Java解法

public class Solution { public int countPrimes(int n) { boolean notPrime[] = new boolean[n + 2]; notPrime[0] = notPrime[1] = true; for (int i = 2; i * i < n; i++) { if (!notPrime[i]) { int c = i * i; while (c < n) { notPrime[c] = true; c += i; } } } int ans = 0; for (int i = 0; i < n; i++) { if (!notPrime[i]) ans ++; } return ans; } }

 

參考:http://bookshadow.com/weblog/2015/04/27/leetcode-count-primes/

相關文章
相關標籤/搜索