仅打印第n个素数序列,python

时间:2014-12-21 19:04:49

标签: python

我正在尝试在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中执行此操作,但是,它将如何完成,以及最好的方法是什么,而不必添加太多我在这里没有的新变量,(尽管我会很好这样做)。帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

只有在第Y个号码时才打印:

if isprime:
    Y += 1
    if Y == X:
        print P

答案 1 :(得分:1)

添加条件,以便 用户想要打印所有数字时,您已达到序列的最终素数,将打印该数字。 (我还用一些更具描述性的变量名替换了一些变量名,并对其进行了修改,以便将函数作为唯一参数传递给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)