简体   繁体   English

如何在python中找到素数?

[英]How to find the prime numbers in python?

I am a beginner in python. 我是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. 我过去在MATLAB中工作,现在我需要为实习学习python。 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. 您还能告诉我如何解决缩进问题,或了解有关python中缩进的更多信息。 I got to know identation in python is very important. 我知道python中的标识非常重要。 I am using python 3 version. 我正在使用python 3版本。

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. 对于一般的算法,如果您在浏览器中搜索“ Python find primes”,那么您会找到比我们这里可以更好地解释这一点的参考。

This might be a little advanced, but it is my favorite combination of brevity, code clarity, and speed for n below about a billion. 这可能有点先进,但这是我最喜欢的简洁,代码清晰和n小于10亿的速度的组合。 Beyond that, C++ is your friend. 除此之外,C ++是您的朋友。

Credit to @Robert William Hanks for the brilliant sieve function. 感谢@Robert William Hanks出色的筛分功能。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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