素数是收到的整数因子

时间:2018-05-28 04:27:17

标签: python

我一直试图完成这项任务,但我无法得到所要求的内容,即:在 Python 3 中,要求用户输入一个整数(1, 1000)。在第一个素数2,3,5,7的列表中,打印那些作为接收整数因子的素数 我希望能帮助我做到这一点。

1 个答案:

答案 0 :(得分:0)

def get_primes(n):
    out = list()
    sieve = [True] * (n+1)
    for p in range(2, n+1):
        if (sieve[p]):
            out.append(p)
            for i in range(p, n+1, p):
                sieve[i] = False
    return out


def get_factors(n):
    output = list()
    for i in range(1, n + 1):
        if n % i == 0:
            output.append(i)
    return output

# input_number = input('Enter a number')
# input_number = int(input_number)
input_number = 30

primes = get_primes(input_number+1) # [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]

factors = get_factors(input_number) # [1, 2, 3, 5, 6, 10, 15, 30]

prime_factors = list()
for i in factors:
    if i in primes:
        prime_factors.append(i)

print(prime_factors)

输出:

[2, 3, 5]

获得素数的代码: Print series of prime numbers in python