Java计算小于N的质数_[leetcode] 204. Count Primes 统计小于非负整数n的素数的个数

题目大意

204. Count Primes

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

Example:

Input: 10

Output: 4

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

题目大意:

统计小于非负整数n的素数的个数

提示:n的范围是100,000到5,000,000

解题思路

参考文献:

abd19314719b3ed3633330e9876cf3b2.gif

伪代码

Input: an integer n > 1.

Let A be an array of Boolean values, indexed by integers2to n,

initially all set to true.for i = 2, 3, 4, ..., notexceeding √n:if A[i] istrue:for j = i2, i2+i, i2+2i, i2+3i, ..., notexceeding n:

A[j] :=false.

Output: all i such that A[i]is true.

Python解法

起初Python的时间限制过于严格,采用Python解题对于测试样例5000000总是返回Time Limit Exceeded,后来管理员放宽了Python的时限。

classSolution(object):defcountPrimes(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

p= x *xwhile p

is_prime[p]=False

p+=x

x+= 1

returnsum(is_prime)defcountPrimes_v0(self, n):""":type n: int

:rtype: int"""is_prime= [True] * max(n, 2)

is_prime[0], is_prime[1] =False, Falsefor x in range(2, int(n ** 0.5) + 1):ifis_prime[x]:

p= x *xwhile p

is_prime[p]=False

p+=xreturn sum(is_prime)

Java解法

public classSolution {

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

notPrime[c]=true;

c+=i;

}

}

}

int ans=0;for (int i = 0; i < n; i++) {if(!notPrime[i])

ans++;

}returnans;

}

}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值