在python中打印素数系列 [英] Print series of prime numbers in python

查看:46
本文介绍了在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中打印素数系列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆