簡體   English   中英

在python中為范圍生成非素數

[英]generate non-prime numbers for a range in python

我們必須生成一個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
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()
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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM