简体   繁体   English

我还能如何将while循环与[included function]一起使用,以仅对给定范围内的质数求和?

[英]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 . 我正在寻找可以超出未知变量n k is the number of primes. k是素数。 is_prime() is a function that returns True if the argument is a prime, and False otherwise. is_prime()是一个函数,如果参数为素数则返回True ,否则返回False

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. 随着n的值变大,我的代码开始不起作用。 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 . 我希望k仅在is_prime返回True时增加,并且total将是运行总计,确保素数之和不超过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() ? 如何使用while循环,for循环或if / elif / else来解决此问题,而又不使用sum()类的其他函数呢?

Your code doesn't seem to have a problem in it, assuming is_prime actually does what it's supposed to. 您的代码似乎没有问题,假设is_prime确实执行了预期的工作。 Perhaps your n was just too large and looking for enough prime numbers to reach n took too long. 也许您的n太大,并且寻找足够的质数来达到n花费的时间太长。

If any errors were raised you should have specified them, other than that, I don't really see any problem with the code. 如果出现任何错误,您应该已经指定了它们,除此之外,我看不到代码有任何问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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