こんにちは。ぽこです!
今回は、Pythonを使って素数判定をするプログラムを作成します。
問題
1から100までで素数のみを出力するプログラムを作成しなさい。
回答
1 2 3 4 5 6 |
for i in range(1, 101): for j in range(2, i): if i%j == 0: break else: print(i) |
簡単に作成すると、このようになります。
1〜100の数字に対してそれぞれ1〜対象の数までで割っていき、割り切れたらその数は素数ではないので次の数に行きます。
3から5まで確認してみると、
3 ÷ 2 = 1 あまり 1 ←あまりが0でないのでこれは素数として出力して次の数字へ
4 ÷ 2 = 2 あまり 0 ←あまりが0なのでこれは素数ではない。出力せずに次の数字へ
5 ÷ 2 = 2 あまり 1 ←あまりが0でないので次の数字へ
5 ÷ 3 = 1 あまり 2 ←あまりが0でないので次の数字へ
5 ÷ 4 = 1 あまり 1 ←あまりが0でない。すべてのループで割り切れなかったので、素数として出力して次の数字へ
…
このような流れとなっています。
コメント
bu güzel paylaşım için teşekkürler
Thank you for writing this informative blog post about the best places to visit in Europe. You have given a great overview of the different countries and cultures that Europe has to offer. I love how you have included some beautiful photos and videos to illustrate your points. I have always wanted to travel to Europe and your post has inspired me to plan my next trip. I appreciate your recommendations and suggestions.