python - Prime numbers using sieve of erathosthenes
问题描述
So I am new to programming in python(and in general) and was doing some coding challenges. I came across this 'prime numbers using the sieve method' challenge. I have successfully managed to attempt it however I feel like my logic needs improvement.
So what I did was use 3 while loops in python, the code works as intended, gives me a set of prime numbers however I cannot find a way to condense it.
import sys
n = int(sys.argv[1])
ls = []
i = 2
while i <= n:
ls.append(i)
i += 1
i = 0
while i < len(ls):
if i == 0:
pass
else:
ls[i] = ''
i += 2
i = 1
while i < len(ls):
if i == 1:
pass
else:
ls[i] = ''
i += 3
i = 0
while i < len(ls):
if i == 0:
pass
else:
ls[i] = ''
i += 5
i = 0
primes = []
while i < len(ls):
if ls[i] != '':
primes.append(ls[i])
i += 1
for prime in primes:
print(prime,end=', ')
As the ceo of nvidia once said, 'it just works' but clearly not in the best way :D
解决方案
Your code thinks 49 is prime, which is not awesome. Making a while loop for each prime just doesn't work.
Here's a simple version that does:
import math
def primesLessThan(N):
seive = [True] * N
seive[0] = seive[1] = False
for i in range(2,int(math.sqrt(N))+1):
if (seive[i]): # i is prime
for j in range(2*i,N,i): # all multiples of i >= 2i
seive[j] = False # j is composite since i is a factor
return [p for p in range(2,N) if seive[p]]
print(primesLessThan(500))
推荐阅读
- google-apps-script - 如何在单独的选项卡上插入一行并保留一列公式?
- azure - QnA Maker 普遍可用与预览:它找不到答案
- node.js - 找不到模块:错误:无法解析“路径”
- bash - 如何创建监听信号的 bash 脚本
- javascript - 来回旋转元素
- php - 如何在没有 Composer 的情况下使用 phpFastCache 缓存查询?
- azure - 具有应用程序网关和 NAT 规则的 Azure VMSS
- google-bigquery - Big Query 用户定义函数显着减慢查询速度
- web-scraping - 如何用 Pentaho 解析 HTML 文件?
- c# - 包含不工作的 Lambda 表达式