简体   繁体   中英

I want a list of all the prime numbers that are smaller than a integer

Hey so i have these two functions. The first one checks whether a number is a prime number which works. The second one is supposed to take a number and have all the prime numbers that are smaller than that number added into a sorted list. This is the code i have right now,

def is_prime(n):
    flag = True
    if n == 1:
        flag = False
    for i in range(2, n):
        if (n % i) == 0:
            flag = False
    return flag


def primes(num):
    primelist = []
    flag = is_prime(num)
    for i in range(1, num - 1):
        if flag == True:
            primelist.append(num)
    return sorted(primelist)

How would i go about adding all the prime numbers lower than a integer into the list?

You've almost got it!

The issue in your primes function is that flag is computed outside of the loop. So it's computed only once for the input num .

Instead, it should be computed for every loop entry.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM