我已经从用户那里获得了输入并将其因素放到新列表中。如何检查列表中的素数。
a=int(input())
b=[]
for x in range(2,a):
if(a%x)==0:
b.append(x)
print(b)
答案 0 :(得分:0)
在这里您可以打印因子列表,然后遍历因子列表,此程序将打印出素数。除了打印它,您还可以通过将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]
仍将运行。 注意:我将其从仅打印数字更改为将数字附加到数组,然后打印出数组。
答案 1 :(得分:0)
这里是一个底线,您可以通过更改1和150来更改上下限。将其分配给变量。虽然不如SoA快
[i for i in range(1,150) if all(i%j for j in range(2,int(i**(1/2))+1)) and i != 1]