我是编程世界的新手。我只是在python中编写这段代码来生成N个素数。用户应输入N的值,即打印出的素数总数。我写了这段代码,但它没有抛出所需的输出。相反,它打印素数直到第N个数字。 例如:用户输入N = 7的值。 期望的输出:2,3,5,7,11,13,19 实际输出:2,3,5,7
请告知。
i=1
x = int(input("Enter the number:"))
for k in range (1, (x+1), 1):
c=0
for j in range (1, (i+1), 1):
a = i%j
if (a==0):
c = c+1
if (c==2):
print (i)
else:
k = k-1
i=i+1
答案 0 :(得分:31)
使用正则表达式:)
#!/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
答案 1 :(得分:15)
David Eppstein实施超快速筛选 - 我的PC上前1000个素数需要0.146秒:
def gen_primes():
""" Generate an infinite sequence of prime numbers.
"""
# Maps composites to primes witnessing their compositeness.
# This is memory efficient, as the sieve is not "run forward"
# indefinitely, but only as long as required by the current
# number being tested.
#
D = {}
# The running integer that's checked for primeness
q = 2
while True:
if q not in D:
# q is a new prime.
# Yield it and mark its first multiple that isn't
# already marked in previous iterations
#
yield q
D[q * q] = [q]
else:
# q is composite. D[q] is the list of primes that
# divide it. Since we've reached q, we no longer
# need it in the map, but we'll mark the next
# multiples of its witnesses to prepare for larger
# numbers
#
for p in D[q]:
D.setdefault(p + q, []).append(p)
del D[q]
q += 1
primes = gen_primes()
x = set()
y = 0
a = gen_primes()
while y < 10000:
x |= set([a.next()])
y+=1
print "x contains {:,d} primes".format(len(x))
print "largest is {:,d}".format(sorted(x)[-1])
答案 2 :(得分:14)
作为参考,各种声明的解决方案之间存在非常显着的速度差异。这是一些比较代码。 Lennart指出的解决方案被称为“历史性”,Ants提出的解决方案称为“天真”,而RC的解决方案称为“regexp”。
from sys import argv
from time import time
def prime(i, primes):
for prime in primes:
if not (i == prime or i % prime):
return False
primes.add(i)
return i
def historic(n):
primes = set([2])
i, p = 2, 0
while True:
if prime(i, primes):
p += 1
if p == n:
return primes
i += 1
def naive(n):
from itertools import count, islice
primes = (n for n in count(2) if all(n % d for d in range(2, n)))
return islice(primes, 0, n)
def isPrime(n):
import re
# see http://tinyurl.com/3dbhjv
return re.match(r'^1?$|^(11+?)\1+$', '1' * n) == None
def regexp(n):
import sys
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
return l[:N] # print result list limited to N elements
def dotime(func, n):
print func.__name__
start = time()
print sorted(list(func(n)))
print 'Time in seconds: ' + str(time() - start)
if __name__ == "__main__":
for func in naive, historic, regexp:
dotime(func, int(argv[1]))
我机器上n = 100的输出是:
naive
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541]
Time in seconds: 0.0219371318817
historic
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541]
Time in seconds: 0.00515413284302
regexp
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541]
Time in seconds: 0.0733318328857
正如您所看到的,存在很大的差异。这里再次为1000(删除了主要输出):
naive
Time in seconds: 1.49018788338
historic
Time in seconds: 0.148319005966
regexp
Time in seconds: 29.2350409031
答案 3 :(得分:6)
行k = k-1
没有按照您的想法行事。它没有效果。更改k
不会影响循环。在每次迭代时,k
被分配给范围的下一个元素,因此您在循环中对k
所做的任何更改都将被覆盖。
答案 4 :(得分:4)
这是我最终想出来打印前n个素数的原因:
numprimes = raw_input('How many primes to print? ')
count = 0
potentialprime = 2
def primetest(potentialprime):
divisor = 2
while divisor <= potentialprime:
if potentialprime == 2:
return True
elif potentialprime % divisor == 0:
return False
break
while potentialprime % divisor != 0:
if potentialprime - divisor > 1:
divisor += 1
else:
return True
while count < int(numprimes):
if primetest(potentialprime) == True:
print 'Prime #' + str(count + 1), 'is', potentialprime
count += 1
potentialprime += 1
else:
potentialprime += 1
答案 5 :(得分:3)
你想要的是这样的:
x = int(input("Enter the number:"))
count = 0
num = 2
while count < x:
if isnumprime(x):
print x
count = count + 1
num = num + 1
我会留给你实现“isnumprime()”。 ;) 提示:您只需要使用之前找到的所有基本数字来测试除法。
答案 6 :(得分:2)
你需要的是一个Prime Sieve(一种用于查找素数的快速算法),一个非常简单的算法是Sieve of Eratosthenes(查看维基百科),这里是PHP http://www.scriptol.com/programming/sieve.php的实现
答案 7 :(得分:2)
在我们有N个素数之前,一个接一个地取自然数,检查是否有任何一个迄今为止收集的素数除以它。
如果没有,“yay”,我们有一个新的素数...
就是这样。
>>> def generate_n_primes(N):
... primes = []
... chkthis = 2
... while len(primes) < N:
... ptest = [chkthis for i in primes if chkthis%i == 0]
... primes += [] if ptest else [chkthis]
... chkthis += 1
... return primes
...
>>> print generate_n_primes(15)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
答案 8 :(得分:2)
使用生成器表达式创建所有素数的序列,并将其中的第100个切片。
from itertools import count, islice
primes = (n for n in count(2) if all(n % d for d in range(2, n)))
print("100th prime is %d" % next(islice(primes, 99, 100)))
答案 9 :(得分:1)
最快
import math
n = 10000 #first 10000 primes
tmp_n = 1
p = 3
primes = [2]
while tmp_n < n:
is_prime = True
for i in range(3, int(math.sqrt(p) + 1), 2):
# range with step 2
if p % i == 0:
is_prime = False
if is_prime:
primes += [p]
tmp_n += 1
p += 2
print(primes)
答案 10 :(得分:1)
您可以获取素数输入的数量。按照你的方法,我在这里采用了预定义的10:
import UIKit
import PlaygroundSupport
let formatter = NumberFormatter()
formatter.locale = Locale.current
//formatter.numberStyle = .currency
formatter.minimumFractionDigits = 1
formatter.maximumFractionDigits = 15
formatter.usesGroupingSeparator = true
let number: NSNumber? = formatter.number(from: "0.0004131955")
let unitPrice: Double? = number?.doubleValue
答案 11 :(得分:1)
def isPrime(y):
i=2
while i < y:
if y%i == 0 :
return 0
exit()
i=i+1
return 1
x= raw_input('Enter the position 1st,2nd,..nth prime number you are looking for?: ')
z=int(x)
# for l in range(2,z)
count = 1
n = 2
while count <= z:
if isPrime(n) == 1:
if count == z:
print n
count +=1
n=n+1
答案 12 :(得分:0)
max = input("enter the maximum limit to check prime number");
if max>1 :
for i in range (2,max):
prime=0;
for j in range (2,i):
if(i%j==0):
prime=1;
break
if(prime==0 and i!=0):
print(i,"is prime number");
else:
print("prime no start from 2");
答案 13 :(得分:0)
这是一个简单的递归版本:
import datetime
import math
def is_prime(n, div=2):
if div> int(math.sqrt(n)): return True
if n% div == 0:
return False
else:
div+=1
return is_prime(n,div)
now = datetime.datetime.now()
until = raw_input("How many prime numbers my lord desires??? ")
until = int(until)
primelist=[]
i=1;
while len(primelist)<until:
if is_prime(i):
primelist.insert(0,i)
i+=1
else: i+=1
print "++++++++++++++++++++"
print primelist
finish = datetime.datetime.now()
print "It took your computer", finish - now , "secs to calculate it"
这是一个使用带内存的递归函数的版本!:
import datetime
import math
def is_prime(n, div=2):
global primelist
if div> int(math.sqrt(n)): return True
if div < primelist[0]:
div = primelist[0]
for x in primelist:
if x ==0 or x==1: continue
if n % x == 0:
return False
if n% div == 0:
return False
else:
div+=1
return is_prime(n,div)
now = datetime.datetime.now()
print 'time and date:',now
until = raw_input("How many prime numbers my lord desires??? ")
until = int(until)
primelist=[]
i=1;
while len(primelist)<until:
if is_prime(i):
primelist.insert(0,i)
i+=1
else: i+=1
print "Here you go!"
print primelist
finish = datetime.datetime.now()
print "It took your computer", finish - now , " to calculate it"
希望有所帮助:)
答案 14 :(得分:0)
prime=2
counter = 0
x = int(input("Enter the number:\n"))
while (counter < x):
if all(prime%j!=0 for j in range(2, prime)):
print(prime, "is a prime number")
counter+=1
prime+=1
答案 15 :(得分:0)
count = -1
n = int(raw_input("how many primes you want starting from 2 "))
primes=[[]]*n
for p in range(2, n**2):
for i in range(2, p):
if p % i == 0:
break
else:
count +=1
primes[count]= p
if count == n-1:
break
print (primes)
print 'Done'
答案 16 :(得分:0)
这里的答案很简单,即循环运行'n'次。
n=int(input())
count=0
i=2
while count<n:
flag=0
j=2
while j<=int(i**0.5):
if i%j==0:
flag+=1
j+=1
if flag==0:
print(i,end=" ")
count+=1
i+=1
答案 17 :(得分:0)
您无需声明许多变量,请参见以下代码,简单,并且易于理解。
for num in range(1,50):
for i in range(2,num):
if num%i == 0:
break
else:
print(num,'is a prime')
答案 18 :(得分:0)
/home/user/Downloads/shell
答案 19 :(得分:0)
def isprime(n):
if n <= 1:
return False
for x in range(2, n):
if n % x == 0:
return False
else:
return True
def list_prime(z):
y = 0
def to_infinity():
index=0
while 1:
yield index
index += 1
for n in to_infinity():
if y < z:
if isprime(n):
y = y + 1
print(n, end='\n', flush=True)
else:break
print(f'\n {z} prime numbers are as above.')
# put your range below
list_prime(10)
答案 20 :(得分:0)
试试这个:
primeList = []
for num in range(2,10000):
if all(num%i!=0 for i in range(2,num)):
primeList.append(num)
x = int(raw_input("Enter n: "))
for i in range(x):
print primeList[i]
答案 21 :(得分:0)
这是我的版本
import timeit
import math
__author__ = 'rain'
primes = [2]
def is_prime(n):
for prime in primes:
if n % prime == 0:
return False
return True
def find_nth_prime(n):
current_index = 0
while(len(primes) < n):
if current_index == 0:
start_value = 3
end_value = 2 * 2
else:
start_value = primes[current_index - 1] * primes[current_index - 1] + 1
end_value = primes[current_index] * primes[current_index]
for i in range(start_value, end_value):
if is_prime(i):
primes.append(i)
current_index += 1
return primes[n-1]
def solve():
return find_nth_prime(10001)
print solve()
print timeit.timeit(solve, number=10)
我用筛子扫描素数,它很快
只需3.8秒到06秒即可获得10001次素数(10次)。
答案 22 :(得分:0)
在Python V3中使用素数时,我注意到复合(非素数)数可以被整除的最小数字本身总是小于被测数字的平方根的素数。
以下是我对该结果的实现,以计算前N个素数。
0.028S中的前1,000个素数| 0.6S中的前10,000个素数| 14.3S中的前100,000个素数
下面的片段还表明了这一代人花了多长时间,并以漂亮的表格格式打印出素数。
import time
import math
def first_n_Primes(n):
number_under_test = 4
primes = [2,3]
while len(primes) < n:
check = False
for prime in primes:
if prime > math.sqrt(number_under_test) : break
if number_under_test % prime == 0:
check = True
break
if not check:
for counter in range(primes[len(primes)-1],number_under_test-1,2):
if number_under_test % counter == 0:
check = True
break
if not check:
primes.append(number_under_test)
number_under_test+=1
return primes
start_time = time.time()
data = first_n_Primes(1000)
end_time = time.time()
i = 1
while i < len(data)+1:
print('{0: <9}'.format(str(data[i-1])), end="")
if i%10 == 0: print("")
i+=1
print("\nFirst %d primes took %s seconds ---" % (len(data),end_time - start_time))
答案 23 :(得分:0)
尝试使用while循环检查计数,这很容易。找到下面的代码段:
i=1
count = 0;
x = int(input("Enter the number:\n"))
while (count < x):
c=0
for j in range (1, (i+1), 1):
a = i%j
if (a==0):
c = c+1
if (c==2):
print (i)
count = count+1
i=i+1
答案 24 :(得分:0)
这可能会有所帮助:
import sys
from time import time
def prime(N):
M=100
l=[]
while len(l) < N:
for i in range(M-100,M):
num = filter(lambda y :i % y == 0,(y for y in range(2 ,(i/2))))
if not num and i not in [0,1,4]:
l.append(i)
M +=100
return l[:N]
def dotime(func, n):
print func.__name__
start = time()
print sorted(list(func(n))),len(list(func(n)))
print 'Time in seconds: ' + str(time() - start)
if __name__ == "__main__":
dotime(prime, int(sys.argv[1]))
答案 25 :(得分:0)
n=int(input("Enter the number:: "))
for i in range(2,n):
p=i
k=0
for j in range(2,p-1):
if(p%j==0):
k=k+1
if(k==0):
print(p)
答案 26 :(得分:0)
这段代码很混乱,我无法弄清楚你在编写它时想到的是什么,或者你想要完成什么。在尝试弄清楚如何编写代码时,我建议的第一件事就是首先使变量名称具有极强的描述性。这将帮助您直接了解您正在做的事情,并且它也将帮助那些试图帮助您向您展示如何直接理解您的想法的人。
话虽如此,这是一个实现接近目标的示例程序:
primewanted = int(input("This program will give you the nth prime.\nPlease enter n:"))
if primewanted <= 0:
print "n must be >= 1"
else:
lastprime = 2 # 2 is the very first prime number
primesfound = 1 # Since 2 is the very first prime, we've found 1 prime
possibleprime = lastprime + 1 # Start search for new primes right after
while primesfound < primewanted:
# Start at 2. Things divisible by 1 might still be prime
testdivisor = 2
# Something is still possibly prime if it divided with a remainder.
still_possibly_prime = ((possibleprime % testdivisor) != 0)
# (testdivisor + 1) because we never want to divide a number by itself.
while still_possibly_prime and ((testdivisor + 1) < possibleprime):
testdivisor = testdivisor + 1
still_possibly_prime = ((possibleprime % testdivisor) != 0)
# If after all that looping the prime is still possibly prime,
# then it is prime.
if still_possibly_prime:
lastprime = possibleprime
primesfound = primesfound + 1
# Go on ahead to see if the next number is prime
possibleprime = possibleprime + 1
print "This nth prime is:", lastprime
这段代码:
testdivisor = 2
# Something is still possibly prime if it divided with a remainder.
still_possibly_prime = ((possibleprime % testdivisor) != 0)
# (testdivisor + 1) because we never want to divide a number by itself.
while still_possibly_prime and ((testdivisor + 1) < possibleprime):
testdivisor = testdivisor + 1
still_possibly_prime = ((possibleprime % testdivisor) != 0)
可能会被有点慢,但可能更容易理解的取代:
# Assume the number is prime until we prove otherwise
still_possibly_prime = True
# Start at 2. Things divisible by 1 might still be prime
for testdivisor in xrange(2, possibleprime, 1):
# Something is still possibly prime if it divided with a
# remainder. And if it is ever found to be not prime, it's not
# prime, so never check again.
if still_possibly_prime:
still_possibly_prime = ((possibleprime % testdivisor) != 0)
答案 27 :(得分:-1)
这可能会有所帮助:
def in_prime(n):
p=True
i=2
if i**2<=n:
if n%i==0:
p=False
break
if (p):
return n
答案 28 :(得分:-1)
我不熟悉Python所以我正在编写C计数器部分(懒得编写伪代码..:P) 找到前n个素数.. //打印所有素数..不打扰制作数组并返回它等。
void find_first_n_primes(int n){
int count = 0;
for(int i=2;count<=n;i++){
factFlag == 0; //flag for factor count...
for(int k=2;k<sqrt(n)+1;k++){
if(i%k == 0) // factor found..
factFlag++;
}
if(factFlag==0)// no factors found hence prime..
{
Print(i); // prime displayed..
count++;
}
}
}
答案 29 :(得分:-1)
n=1
c=0
while n>0:
for i in range(2,n):
if n%i == 0:
break
else:
print(n,'is a prime')
c=c+1
n=n+1
if c==1000:
break
答案 30 :(得分:-3)
def Isprime(z):
'''returns True if the number is prime OTW returns false'''
if z<1:
return False
elif z==1:
return False
elif z==2:
return True
else:
for i in range(2,z):
if z%i==0:
return False
else:
return True
这就是我这样做的方式。当然,有很多方法可以做到。