我编写了以下用于查找N素数的代码。但是,我无法将其存储在列表中。
def prime(n):
global count
s=0
flag=0
ls=[]
for i in range(2,n/2+1):
if(n%i==0):
flag=1
break
if(flag==0):
print n
ls.append(n)
count=count+1
print ls
# main pro
n=input("Enter the number of prime numbers to be displayed: ")
print"The prime numbers are:"
count=0
x=2
while(count<n):
prime(x)
x+=1
我想要的输出应该是:
Enter the number of prime numbers to be displayed: 5
[2, 3, 5, 7, 11]
但是当我运行程序时,输出为:
Enter the number of prime numbers to be displayed: 5
The prime numbers are:
2
[2]
3
[3]
[]
5
[5]
[]
7
[7]
[]
[]
[]
11
[11]
如何在不更改上述代码的情况下将素数添加到列表中? 我应该在以后的部分附加元素吗?我是Python新手,所以非常感谢所有帮助!谢谢!
答案 0 :(得分:0)
这将返回count
素数组:
def get_primes(count):
primes = []
n = 2
while len(primes) != count:
for i in range(2, n // 2 + 1):
if n % i == 0:
break
else:
primes.append(n)
n += 1
return primes
你可以像这样使用它:
n=input("Enter the number of prime numbers to be displayed: ")
array_of_n_prime_numbers = get_primes(n)
print("The prime numbers are:", array_of_n_prime_numbers)
答案 1 :(得分:0)
试试这个
def prime(x):
if x<1:
return []
prime_numbers = [2,3]
if x<3:
return prime_number[:x]
for i in range(2,x):
next_pn = prime_numbers[-1]+2
while any(not(next_pn%pn) for pn in prime_numbers):
next_pn += 2
prime_numbers.append(next_pn)
return prime_numbers
N = input("Enter the number of prime numbers to be displayed:")
print (prime(int(N)))
输出
Enter the number of prime numbers to be displayed:5
[2, 3, 5, 7, 11]
不需要遍历所有数字,而是可以在它之前只遍历素数。
答案 2 :(得分:0)
这是一个简单的方法:
def prime(n):
ls = [2,3]
if (n < 3):
return ls[:n]
for i in range(2,n):
generate = ls[-1]+2
while any(not(generate%num) for num in ls):
generate += 2
ls.append(generate)
return ls
n = int(input("Enter the number of prime numbers to be displayed:"))
print (prime(n))
输入为5时输出:
[2, 3, 5, 7, 11]