找到在python第1000素数之和 [英] Find sum of first 1000 prime numbers in python

查看:221
本文介绍了找到在python第1000素数之和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个程序,计算uptill 1000的程序如下素数之和:

I have written a program which counts the sum of the primes uptill 1000. The program is as follows:

limit = 1000

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

sum = 0
for i in range(2, int(limit+1)):
    if is_prime(i):
        sum = sum + i
        count += 1
print sum

我可以做什么样的变化找到1000的素数,而不是高达1000个号码?另外,我要寻找的空间复杂度为O(1)的时间复杂度为O(n)(据我所知其他的方法可以做到这一点:-)如筛埃拉托色尼,并找到黄金,而迭代高达开方(N) http://www.geeksforgeeks.org/print-所有黄金的因素 - 对的一给定数/

请纠正我,如果我错了一些地方。谢谢你。

Please correct me if I am going wrong some where. Thank you.

推荐答案

只是根据你的code找到限制小的改进素数,而不是限制的数字。

Just a small improvement based on your code to find limit primes instead of limit numbers.

limit = 1000

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

sum = 0
num = 2
for i in xrange(limit):
    while not is_prime(num):
        num += 1
    sum += num
    num += 1 # sorry, miss this
print sum

和你也可以使用一个循环寻找一定的你感兴趣的东西的时候,它可能是味道只是一个问题。

And you could also use a single loop when looking for certain amount of things you are interested in, it could be just a matter of taste.

limit = 1000

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

sum = 0
count = 0
num = 2
while count != limit:
    if is_prime(num):
        sum += num
        count += 1
    num += 1

print sum

这篇关于找到在python第1000素数之和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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