Python練習(六)
阿新 • • 發佈:2017-09-20
素數 開關
Python練習(六)
給一個數,判斷它是否是素數(質數):
除了1和它自身外,不能被小於它的正整數整除的就是素數。
簡化點就是:能整除,不是素數
不能整除,是素數
可以參考另一篇《Python練習(三)》中有介紹如何計算出1-100之內的所有素數
num = int(input(‘please enter a number: >>> ‘)) on_off = 0 ‘‘‘開關‘‘‘ for i in range(2,num): if num%i == 0: on_off = 1 break else: on_off = 0 if on_off == 1: print(‘可以整除,開關設為1,不是素數‘) else: print(‘不可以整除,開關賦為0,是素數‘)
輸出結果:
please enter a number: >>> 11 不可以整除,開關賦為0,是素數
please enter a number: >>> 4 可以整除,開關設為1,不是素數
please enter a number: >>> 8 可以整除,開關設為1,不是素數
please enter a number: >>> 97 不可以整除,開關賦為0,是素數
Python練習(六)