Leetcode 204. Count Primes

Source: Internet
Author: User

Topic Overview:

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.

Problem Solving Ideas:

The idea is divided into the following steps:

    • First, an array of length n is set to Prime, which is used from 0 to n-1.
    • Set prime[0] and prime[1] to false, since 0 and 1 are not prime numbers.
    • Next, for the critical step, set the not prime number to false for the integer less than n.
      • If a positive integer can be expressed as a product of two numbers (except 1), then the number is not a prime, so we need to find two numbers, and if the product of these two numbers is less than n, the result of multiplying is not a prime.
      • First, the first multiplier I, we need to take I as a prime number, because the non-prime can certainly be expressed by prime numbers, the calculation of the product of non-prime is caused by unnecessary additional computation. I only need to consider the value of 2 to sqrt (n) +1, because when the I>SQRT (n), I is larger than the number of itself, the result is necessarily greater than n, and if I multiplied by its own small number, it is redundant calculation, because this part of the calculation has been calculated by I in the previous value.
      • Next is the second multiplier J, J is a multiplier, the purpose is to remove the multiples of the number of primes in the N range.
    • The last step is to count the number of true digits remaining in the prime, that is, the number of primes
Code:
classsolution (object):defcountprimes (self, n):""": Type N:int:rtype:int"""        ifN <=2:            return0 Prime= [true]*N prime[0],prime[1] =False,false forIinchRange (2,int (n**0.5) +1):            ifPrime[i]: prime[i*I:N:I] = [False]*len (prime[i*i:n:i])returnSUM (Prime)

Leetcode 204. Count Primes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.