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

‘‘‘
写一个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()

结果如图

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

 

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

上一篇:微信公众号测试号申请及本地开发环境配置


下一篇:小程序 二级联动 区--街道