我正在尝试用 Python 编写一个程序,它可以打印素数序列的第 1 到第 n 个数,或者只打印素数序列的第 n 个数。这是代码。
import math
P = 2
X = raw_input('Choose a number: ')
Y = 1
def prime(P, Y):
Choice = raw_input('Select 1 to print X numbers of the Prime sequence. \nSelect 2 to print the Xth number in the Prime sequence. \nWhat is your choice: ')
if Choice == "1":
while Y <= int(X):
isprime = True
for x in range(2, int(P) - 1):
if P % x == 0:
isprime = False
break
if isprime:
print P
Y += 1
P += 1
elif Choice == "2":
prime(P, Y)
基本上,我有第一部分,所以它打印素数序列的第 1 到第 n 个数。但是,我完全不知道如何让它只计算第 n 个素数,其中第 n 个素数是通过原始输入给出的。必须可以在 python 中执行此操作,但是,它是如何完成的,最好的方法是什么,而不必添加太多我这里没有的新变量,(尽管我会很好这样做)。帮助将不胜感激。
最佳答案
添加一个条件,如果或者用户想要打印所有数字,或者您已经达到了序列的最终素数,那么该数字将被打印。 (我还用更具描述性的名称替换了一些变量名称,并对其进行了更改,以便函数将 number_of_primes
作为其唯一参数传递,这似乎更有意义。)
def print_primes(X):
choice = raw_input('Select 1 to print X numbers of the Prime sequence. \nSelect 2 to print the Xth number in the Prime sequence. \nWhat is your choice: ')
count = 1
n = 2
while count <= X:
is_prime = True
for i in range(2, int(n) - 1):
if n % i == 0:
is_prime = False
break
if is_prime:
if choice == "1" or count == X:
print n
count += 1
n += 1
number_of_primes = int(raw_input('Choose a number: '))
print_primes(number_of_primes)
关于python - 只打印第n个素数序列,python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27592719/