寫個小程序查看500以內的質數
阿新 • • 發佈:2018-10-04
小程序 圖片 oba info style div sta prim http
‘‘‘ 寫一個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以內的質數