质数码的优化

编程入门 行业动态 更新时间:2024-10-25 12:15:49
本文介绍了质数码的优化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是我用python编写的代码,用于计算小于给定数的素数之和.我还能做些什么来优化它?

This is my code in python for calculation of sum of prime numbers less than a given number. What more can I do to optimize it?

import math primes = [2,] #primes store the prime numbers for i in xrange(3,20000,2): #i is the test number x = math.sqrt(i) isprime = True for j in primes: #j is the devider. only primes are used as deviders if j <= x: if i%j == 0: isprime = False break if isprime: primes.append(i,) print sum (primes,)

推荐答案

您可以使用一种不同的算法,称为 Eratosthenes 的筛网 这将更快但需要更多的内存.保留一组标志,表示每个数字是否为素数,并且对于每个新素数,将该素数的所有倍数设置为零.

You can use a different algorithm called the Sieve of Eratosthenes which will be faster but take more memory. Keep an array of flags, signifying whether each number is a prime or not, and for each new prime set it to zero for all multiples of that prime.

N = 10000 # initialize an array of flags is_prime = [1 for num in xrange(N)] is_prime[0] = 0 # this is because indexing starts at zero is_prime[1] = 0 # one is not a prime, but don't mark all of its multiples! def set_prime(num): "num is a prime; set all of its multiples in is_prime to zero" for x in xrange(num*2, N, num): is_prime[x] = 0 # iterate over all integers up to N and update the is_prime array accordingly for num in xrange(N): if is_prime[num] == 1: set_prime(num) primes = [num for num in xrange(N) if is_prime[num]]

如果您使用有效的位数组,您实际上可以为相当大的 N 执行此操作,例如在 这个示例中(向下滚动页面,您会找到一个埃拉托色尼筛法示例).

You can actually do this for pretty large N if you use an efficient bit array, such as in this example (scroll down on the page and you'll find a Sieve of Eratosthenes example).

更多推荐

质数码的优化

本文发布于:2023-11-29 23:03:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647896.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:质数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!