1. 程式人生 > >python指令碼5_求素數

python指令碼5_求素數

#求素數
#素數:只能被1和它自己整除
n = int(input('Please input a number >>>'))
flag = False
for i in range(2,n):
    if n % i == 0:   #找到條件是什麼
        flag = True
        print(i)
        break
if flag:
    print(n,'is not a prime number.')
else:
    print(n,'is a prime number.')

2、或者如下:

#求素數
#素數:只能被1和它自己整除
n = int(input('Please input a number >>>')) flag = False for i in range(2,n): if n % i == 0: #找到條件是什麼 print(n,'is not a prime number.') break else: print(n,'is a prime number.')

 3、或者如下:

#求素數
#正向思維,能被1 和本身整除
#
n = int(input('Please input a number: '))
i  
= 0 for m in range(1,n+1): if n%m == 0: i += m if i == (1+n): print(n,'is a prime number.') else: print(n,'is not a prime number.')