简体   繁体   中英

How else can I use the while-loop with the [included function] to sum only prime numbers from a given range?

I'm looking for the specific number of primes that I can add together before exceeding unknown variable n . k is the number of primes. is_prime() is a function that returns True if the argument is a prime, and False otherwise.

What I have attempted:

i = 1
total = 2
k = 0

while total <= n:
    i += 1
    if is_prime(i):
        k += 1
        total += i

my code begins to not work as the value of n gets larger. I was hoping k would increment only when is_prime returns True , and total would be a running total making sure the sum of the primes do not exceed n . How can I solve this problem using either a while-loop, for-loop, or if/elif/else, and without the use of other functions such as sum() ?

Your code doesn't seem to have a problem in it, assuming is_prime actually does what it's supposed to. Perhaps your n was just too large and looking for enough prime numbers to reach n took too long.

If any errors were raised you should have specified them, other than that, I don't really see any problem with the code.

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