在python中找到前N个素数 [英] To find first N prime numbers in python
本文介绍了在python中找到前N个素数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是编程世界的新手.我只是在 python 中编写这段代码来生成 N 个素数.用户应输入 N 的值,即要打印的素数总数.我已经编写了这段代码,但它没有抛出所需的输出.相反,它打印素数直到第 N 个数字.
I am new to the programming world. I was just writing this code in python to generate N prime numbers. User should input the value for N which is the total number of prime numbers to print out. I have written this code but it doesn't throw the desired output. Instead it prints the prime numbers till the Nth number.
例如:用户输入 N = 7 的值.
For example: User enters the value of N = 7.
期望输出:2、3、5、7、11、13、19
Desired output: 2, 3, 5, 7, 11, 13, 19
实际输出:2、3、5、7
Actual output: 2, 3, 5, 7
请多多指教.
i = 1
x = int(input("Enter the number:"))
for k in range(1, x+1):
c = 0
for j in range(1, i+1):
a = i % j
if a == 0:
c = c + 1
if c == 2:
print(i)
else:
k = k - 1
i = i + 1
推荐答案
使用正则表达式 :)
#!/usr/bin/python
import re, sys
def isPrime(n):
# see http://www.noulakaz.net/weblog/2007/03/18/a-regular-expression-to-check-for-prime-numbers/
return re.match(r'^1?$|^(11+?)\1+$', '1' * n) == None
N = int(sys.argv[1]) # number of primes wanted (from command-line)
M = 100 # upper-bound of search space
l = list() # result list
while len(l) < N:
l += filter(isPrime, range(M - 100, M)) # append prime element of [M - 100, M] to l
M += 100 # increment upper-bound
print l[:N] # print result list limited to N elements
这篇关于在python中找到前N个素数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文