前 100 个素数 [英] First 100 prime numbers

查看:68
本文介绍了前 100 个素数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有多种方法可以找到前 100 个素数,但请帮助我解决问题.我发现 count 的值正在增加,但由于某种原因 while 循环条件不适用:

count = 0而(计数 <= 20):对于范围内的 i (2, 20):对于范围内的 j (2, i):如果我<j:打印(数字",i,是素数")elif i % j == 0:休息别的:打印(数字",i,是素数")计数 = 计数 + 1打印(计数)

解决方案

您可以使用 Eratosthenes 筛网 找到前 n 个素数:

def primes_upto(limit):素数 = [真] * 限制对于范围内的 n(2,限制):如果素数[n]:yield n # n 是素数对于范围内的 c (n*n, limit, n):prime[c] = False # 标记复合

要获得前 100 个质数:

<预><代码>>>>列表(primes_upto(542))[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, ... ,499、503、509、521、523、541]

要找到前 n 个素数,您可以估计第 n 个素数(通过上限) 或使用 无限质数生成器 并根据需要获取尽可能多的数字,例如,使用 list(itertools.islice(gen, 100)).

I know there are a number of ways to find the first 100 prime numbers but please help me in my approach. I find the value of count to be increasing but for some reason the while loop condition doesn't apply:

count = 0

while(count <= 20):
    for i in range(2, 20):
        for j in range(2, i):
            if i < j:
                print("The number",i,"is prime")
            elif i % j == 0:
                break
        else:
            print("The number",i,"is prime")
            count = count + 1
            print(count)

解决方案

You could use Sieve of Eratosthenes to find the first n prime numbers:

def primes_upto(limit):
    prime = [True] * limit
    for n in range(2, limit):
        if prime[n]:
            yield n # n is a prime
            for c in range(n*n, limit, n):
                prime[c] = False # mark composites

To get the first 100 primes:

>>> list(primes_upto(542))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, ... ,
 499, 503, 509, 521, 523, 541]

To find the first n primes, you could estimate n-th prime (to pass the upper bound as the limit) or use an infinite prime number generator and get as many numbers as you need e.g., using list(itertools.islice(gen, 100)).

这篇关于前 100 个素数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆