‘‘‘ 写一个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()
结果如图
原文地址:https://www.cnblogs.com/caizhw3/p/9741094.html
时间: 2024-10-09 21:13:43