在python中打印素数系列

编程入门 行业动态 更新时间:2024-10-27 16:23:44
本文介绍了在python中打印素数系列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在打印从一到一百的一系列素数时遇到问题.我想不通我的代码有什么问题.

I was having issues in printing a series of prime numbers from one to hundred. I can't figure our what's wrong with my code.

这是我写的;它打印所有奇数而不是素数:

Here's what I wrote; it prints all the odd numbers instead of primes:

for num in range(1, 101): for i in range(2, num): if num % i == 0: break else: print(num) break

推荐答案

您需要检查从 2 到 n-1 的所有数字(实际上到 sqrt(n),但好吧,让它成为 n).如果 n 可被任何数字整除,则它不是质数.如果一个数是素数,则打印它.

You need to check all numbers from 2 to n-1 (to sqrt(n) actually, but ok, let it be n). If n is divisible by any of the numbers, it is not prime. If a number is prime, print it.

for num in range(2,101): prime = True for i in range(2,num): if (num%i==0): prime = False if prime: print (num)

你可以写得更短、更像pythonic:

You can write the same much shorter and more pythonic:

for num in range(2,101): if all(num%i!=0 for i in range(2,num)): print (num)

正如我已经说过的,最好检查除数不是从 2 到 n-1,而是从 2 到 sqrt(n):

As I've said already, it would be better to check divisors not from 2 to n-1, but from 2 to sqrt(n):

import math for num in range(2,101): if all(num%i!=0 for i in range(2,int(math.sqrt(num))+1)): print (num)

对于像 101 这样的小数字没有关系,但是对于 10**8 来说差别会非常大.

For small numbers like 101 it doesn't matter, but for 10**8 the difference will be really big.

您可以通过将检查的范围增加 2 来进一步改进它,从而只检查奇数.像这样:

You can improve it a little more by incrementing the range you check by 2, and thereby only checking odd numbers. Like so:

import math print 2 for num in range(3,101,2): if all(num%i!=0 for i in range(2,int(math.sqrt(num))+1)): print (num)

由于在第一次循环中选择了奇数,在第二次循环中没有需要检查偶数,所以 'i' 值可以从 3 开始跳过了 2.

As in the first loop odd numbers are selected, in the second loop no need to check with even numbers, so 'i' value can be start with 3 and skipped by 2.

import math print 2 for num in range(3,101,2): if all(num%i!=0 for i in range(3,int(math.sqrt(num))+1, 2)): print (num)

更多推荐

在python中打印素数系列

本文发布于:2023-10-20 22:15:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1512296.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:素数   系列   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!