首页 > 解决方案 > 如何在“列表”中打印素数

问题描述

我已经从用户那里获得了输入并将其因素放入一个新列表中。我如何检查列表中的素数。

a=int(input())
b=[]
for x in range(2,a):
    if(a%x)==0:
        b.append(x)
print(b)

标签: python-3.x

解决方案


在这里,您可以打印因子列表,然后遍历因子列表,该程序将打印出素数。print(n)除了打印它,您还可以通过用其他东西替换它来将它附加到另一个列表中。

import math
a=int(input())
b=[]
for x in range(2,a):
    if(a%x)==0:
        b.append(x)
print(b)



def is_prime(n): #calling a function 
    if n == 2:
        print(n) #if one of the factors is 2 it prints it because it is a prime number

    if n % 2 == 0 or n <= 1: # if it is less than one or is a factor of 2 it returns false and does nothing
        return False

    sqr = int(math.sqrt(n)) + 1

    for divisor in range(3, sqr, 2): #checks for other divisors
        if n % divisor == 0:
            return False
    print(n) #otherwise it prints out the number since it is a prime number



for n in b:  #iterates through the list of factors and checks if they are prime
    is_prime(n)

如果我们运行这个并且我输入 10 它会返回这个:

[2, 5]
2
5

编辑:当您输入一个素数时,它会返回一个空白数组。所以我将代码编辑为:

import math
values = []
def is_prime(n): #calling a function 
    if n == 2:
        values.append(n)

        #print(n) #if one of the factors is 2 it prints it because it is a prime number
        return True
    if n % 2 == 0 or n <= 1: # if it is less than one or is a factor of 2 it returns false and does nothing
        return False

    sqr = int(math.sqrt(n)) + 1

    for divisor in range(3, sqr, 2): #checks for other divisors
        if n % divisor == 0:
            return False
    #print(n) #otherwise it prints out the number since it is a prime number
    values.append(n)
    return True


a=int(input())
b=[]
for x in range(2,a):
    if(a%x)==0:
        b.append(x)
    if is_prime(a)==True: #if the inputted number is prime it automatically appends that number to the list and breaks since prime numbers don't have any other factors
        b.append(a)
        break;

print(b)


for n in b:  #iterates through the list of factors and checks if they are prime
    is_prime(n)
def remove_duplicates(values):  #here it checks for duplicates
    output = []
    seen = set()
    for value in values:
        # If value has not been encountered yet,
        # ... add it to both list and set.
        if value not in seen:
            output.append(value)
            seen.add(value)
    return output

# Remove duplicates from this list.
values = remove_duplicates(values)

print("Here are the prime factors :")    
print(values) #prints out the values

现在,如果您输入一个素数,它会返回:

[7]
Here are the prime factors :
[7]

以及任何其他数字,例如 20 :

[2, 4, 5, 10]
Here are the prime factors :
[2, 5]

仍会运行。注意:我将其从仅打印数字更改为将数字附加到数组然后打印出数组。


推荐阅读