Python 判斷質數,python判斷質數

來源:互聯網
上載者:User

Python 判斷質數,python判斷質數

a = raw_input() #輸入數字a = int(a) #強制轉換成intb=True #一個標記for i in range(2,a): #從2開始迴圈本身    if a%i==0: #如果除了本身和1以外還能被整除        b=False #標記改成False        break #迴圈結束if b:    print 'YES'else:    print 'NO'



素數的Python代碼,講解

這樣寫不知道你能不能理解?

這是等效代碼:

L1 = []
for x in range(1, 100):
list = []
for y in range(2, x/2 + 1):
if x % y == 0:
list.append(y)
if not list:
L1.append(x)
print L1

對於空列表,not [] 返回True

原來的代碼中, if not後面是一個臨時產生的列表, 如果這個列表為空白則表明x沒有任何>=2的因子,x必是素數,於是添加x 到主列表.

[x for x in range(1, 100) if express ]
這樣的語句僅僅在express是True才會添加x
 
助用python編寫“判斷101-200之間有多少個素數”的代碼?

a = 0
list = []
for i in range(101,200,2):
flag=0
for j in range(2,i/2+1):
if (i%j == 0):
flag = 0
break
else:
flag = 1
continue
if flag == 1:
list.append(i)
a+=1
print list
print a
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.