简体   繁体   中英

How to find the prime numbers in python?

I am a beginner in python. But I am not getting why I am still getting an error. I use to work in MATLAB, now I need to learn python for my Internship. Can someone help me out in fixing this problem?

Below is my code to find the number of prime numbers

def prime_number(num):
    myprime = []
    for x in range(2,num):
        prime = True
        if x == 2:
            myprime.append(x)
        else:
            for y in prime:
                if x%y == 0:
                    prime = False
                    break;
            if prime:
                myprime.append(x)

    return myprime

This is my error:

TypeError                                 Traceback (most recent call last)
<ipython-input-87-cd2bf40e6117> in <module>
----> 1 prime_number(100)

<ipython-input-86-169e0a64e50a> in prime_number(num)
     13         else:
     14 
---> 15             for y in prime:
     16 
     17                 if x%y == 0:

TypeError: 'bool' object is not iterable

Can you also tell me how to fix the indentation or learn more about Indentation in python. I got to know identation in python is very important. I am using python 3 version.

Corrected with some help =)

   def prime_number(num):
    myprime = []
    for x in range(1, num):
        if x == 2:
            myprime.append(x)
            continue
        prime = True
        for y in myprime:
            if y <= 1:
                continue
            if x <= 2:
                continue
            if x%y == 0:
                prime = False
                continue
        if prime:
            myprime.append(x)
    return myprime

You confused yourself with variables that are too brief. Been there, done that ...

        for y in prime:

should be

        for y in myprime:

You want to iterate through the list of primes already found. I suggest a global change in variable names:

prime => is_prime
my_prime => prime_list

You'll learn your own naming style as you learn programming.

For the algorithms in general, if you search in your browser for "Python find primes", you'll find references that can explain this much better than we can manage here.

This might be a little advanced, but it is my favorite combination of brevity, code clarity, and speed for n below about a billion. Beyond that, C++ is your friend.

Credit to @Robert William Hanks for the brilliant sieve function. Only the driver code at the bottom is mine.

#!/usr/bin/python -Wall
import sys
def rwh_primes1(n):
    # https://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/2)
    for i in xrange(3,int(n**0.5)+1,2):
        if sieve[i/2]:
            sieve[i*i/2::i] = [False] * ((n-i*i-1)/(2*i)+1)
    return [2] + [2*i+1 for i in xrange(1,n/2) if sieve[i]]

if len(sys.argv) > 1:
    N = int(float(sys.argv[1]))
else:
    N = 10000000    # default: 1e7 10,000,000

p = rwh_primes1(N)
print len(p), "primes found <", N
if N < 1000:
    print p

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM