Finding the nth prime number using Python

前端 未结 4 1755
礼貌的吻别
礼貌的吻别 2020-12-16 08:21

When I run this code, even for just counting to the 10th prime number (instead of 1000) I get a skewed/jacked output--all \"not prime\" titles for my is_composite variable,

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-16 09:13

    See the hints given by MIT for your assignment. I quote them below:

    1. Initialize some state variables

    2. Generate all (odd) integers > 1 as candidates to be prime

    3. For each candidate integer, test whether it is prime

      3.1. One easy way to do this is to test whether any other integer > 1 evenly divides the candidate with 0 remainder. To do this, you can use modular arithmetic, for example, the expression a%b returns the remainder after dividing the integer a by the integer b.

      3.2. You might think about which integers you need to check as divisors – certainly you don’t need to go beyond the candidate you are checking, but how much sooner can you stop checking?

    4. If the candidate is prime, print out some information so you know where you are in the computation, and update the state variables

    5. Stop when you reach some appropriate end condition. In formulating this condition, don’t forget that your program did not generate the first prime (2).

    It could look like this:

    def primes(n):
        # http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
        """ Returns  a list of primes < n """
        sieve = [True] * n
        for i in xrange(3,int(n**0.5)+1,2):
            if sieve[i]:
                sieve[i*i::2*i]=[False]*((n-i*i-1)/(2*i)+1)
        return [2] + [i for i in xrange(3,n,2) if sieve[i]]
    

提交回复
热议问题