在python中为范围生成非素数

时间:2019-06-20 08:12:36

标签: python python-3.x primes

我们必须生成一个python函数以返回非素数。 例如,如果我们通过10,则应返回1 4 6 8 9 10 12 14 15 16

这是到目前为止我尝试过的:

def np_generator(n):
    str1 = [1]
    for num in range(2, 100):
        if num > 1:
            for i in range(2, num):
                if (num % i) == 0:
                    str1.append(num)
                    break
                if(len(str1)==n):
                    print(str1)
        else:
            None
        pass

,它的输出接近解决方案: 当我将12作为n传递时,它返回:

1
[1]
2
[1, 4]
[1, 4]
[1, 4]
3
[1, 4, 6]
[1, 4, 6]
[1, 4, 6]
[1, 4, 6]
[1, 4, 6]
4
[1, 4, 6, 8]
5
6
[1, 4, 6, 8, 9, 10]
[1, 4, 6, 8, 9, 10]
[1, 4, 6, 8, 9, 10]
[1, 4, 6, 8, 9, 10]
[1, 4, 6, 8, 9, 10]
[1, 4, 6, 8, 9, 10]
[1, 4, 6, 8, 9, 10]
[1, 4, 6, 8, 9, 10]
[1, 4, 6, 8, 9, 10]
7
[1, 4, 6, 8, 9, 10, 12]
[1, 4, 6, 8, 9, 10, 12]
[1, 4, 6, 8, 9, 10, 12]
[1, 4, 6, 8, 9, 10, 12]
[1, 4, 6, 8, 9, 10, 12]
[1, 4, 6, 8, 9, 10, 12]
[1, 4, 6, 8, 9, 10, 12]
[1, 4, 6, 8, 9, 10, 12]
[1, 4, 6, 8, 9, 10, 12]
[1, 4, 6, 8, 9, 10, 12]
[1, 4, 6, 8, 9, 10, 12]
8
[1, 4, 6, 8, 9, 10, 12, 14]
9
10
[1, 4, 6, 8, 9, 10, 12, 14, 15, 16]
[1, 4, 6, 8, 9, 10, 12, 14, 15, 16]
[1, 4, 6, 8, 9, 10, 12, 14, 15, 16]
[1, 4, 6, 8, 9, 10, 12, 14, 15, 16]
[1, 4, 6, 8, 9, 10, 12, 14, 15, 16]
[1, 4, 6, 8, 9, 10, 12, 14, 15, 16]
[1, 4, 6, 8, 9, 10, 12, 14, 15, 16]
[1, 4, 6, 8, 9, 10, 12, 14, 15, 16]
[1, 4, 6, 8, 9, 10, 12, 14, 15, 16]
[1, 4, 6, 8, 9, 10, 12, 14, 15, 16]
[1, 4, 6, 8, 9, 10, 12, 14, 15, 16]
[1, 4, 6, 8, 9, 10, 12, 14, 15, 16]
[1, 4, 6, 8,{-truncated-}

,预期的输出是:

1
4
6
8
9
10
12
14
15
16
18
20

2 个答案:

答案 0 :(得分:2)

from math import sqrt
def is_prime(num):
    for i in range(2,int(sqrt(num))+1):
        if num % i == 0:
            return False
    return True
def yield_np(n):
    np_counter = 1
    num_to_print = 1
    while np_counter <= n:
        if num_to_print == 1 or is_prime(num_to_print) == False:
            yield num_to_print
            np_counter+=1
        num_to_print+=1
if __name__ == "__main__":
    n = int(input())
    if n > 0:
        for i in yield_np(n):
            print(i)
    else:
        print()

答案 1 :(得分:0)

def is_prime (x):
    """
    check a number is prime or not
    """
    return True if x in [2,3] else not any (x % n == 0 for n in range (2, int (x ** 0.5) + 1))

def non_prime(n):
    """n = no of non prime user want"""
    non_prime =[1] # list of non prime
    value = 3 # settign counter to start 
    while len(non_prime) < n :
        """looping till  length of non prime reached to n"""           
        if not is_prime(value):
            """ if number is not prime, adding that value to non prime"""
            non_prime.append(value)
        value +=1 # incrementing value after each iteration
    return non_prime # return non prime values

    res = non_prime(10)
    print(res)

输出

[1, 4, 6, 8, 9, 10, 12, 14, 15, 16]