简体   繁体   English

查找所有从10到10000的质数

[英]Find all prime numbers from 10 to 10000

primes = [2,3,5,7]
for n in range(10, 10000):
    isPrime = True
    for d in primes:
        if (n % d) == 0:
            isPrime = False
        else:
            primes.append(n)
            break
print(primes[n])

I have to print all the prime numbers from 10 to 10000 and then append them to the given array of first few prime numbers. 我必须打印从10到10000的所有素数,然后将它们附加到前几个素数的给定数组中。 My code was working earlier as I tested it multiple times. 我的代码在多次测试时运行得更早。 Now it throws me an an error "list index out of range". 现在,它引发了一个错误“列表索引超出范围”。 Not sure what's wrong thought I was on the right track. 不确定我在正确的轨道上怎么了。

I think you should start with something like this 我想你应该从这样的事情开始

You need to iterate over all the prime numbers before you can append to the list. 您需要遍历所有素数,然后才能追加到列表。 Otherwise, you'll always break that loop on odd numbers (you modded with 2) 否则,您将始终在奇数上中断该循环(您用2修改)

primes = [2,3,5,7]
for n in range(10, 10000):
    isPrime = True
    for d in primes:
        if n % d == 0:
            isPrime = False
            break 
    if isPrime:
        primes.append(n)
print(primes)

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

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