写个小程序查看500以内的质数

时间:2018-10-04 08:48:23   收藏:0   阅读:180
‘‘‘
写一个500以内的Eratosthenes筛法找出全部素数
‘‘‘
class node(object):
    def __init__(self,num):
        self.visited = False
        self.isPrime = False
        self.num = num
matrix = [node(i+1) for i in range(500)]
count = 0
def isPrime(num):
    for i in range(2,int(num**0.5)+1):
        if(num % i == 0):
            return False
    return True

def change_sucessors(num):
    for i in range(num+1,len(matrix)):
        if((i+1) % num == 0):
            matrix[i].visited = True
            matrix[i].isPrime = False

def Eratosthenes(start,end):
    global count
    for i in range(start,end):
        if(matrix[i].visited ==False):
            matrix[i].visited = True
            if(isPrime(matrix[i].num)==True):
                count += 1
                matrix[i].isPrime = True
                change_sucessors(matrix[i].num)
def show():
    for i in range(len(matrix)):
        if(matrix[i].isPrime == True):
            print(str(matrix[i].num)+,,end=‘‘)
    print(\nthe num of all is +str(count))

def main():
    Eratosthenes(1,500)
    show()
main()

结果如图

技术分享图片

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!