登录论坛

查看完整版本 : 求助:编写一个找出所有质数的方程


tx1988
2009-10-09, 14:20
今天老师让用 Sieve of Eratosthenes 这个算法去求出所有的prime numbers。 比如你input 50, 这个方程就会return 所有的prime number。 老师给了指导:
1. Create the list {2, 3, 4, . . . , N}.
2. Set p = 2, the smallest prime number.
3. Delete all multiples of p that are ≤ N.
4. Replace p with the first number of the remaining list that is ≥ p; this number is the next largest prime ≤ N.
5. Repeat steps 3 and 4 until p2 > N.
It is straightforward to check that all the remaining numbers on the list are prime.

也就是先创建一个array,然后从p=2开始,将所有能整除p的数去掉,但是怎么在已经建立好的array里去掉某一项?我是第一次接触这个,能给能给个示范怎么编这个程序?

anbcjys
2009-10-10, 08:18
a=[1 2 3];a(2)=[]

haiyunyuan
2009-10-12, 08:31
primes(N) 函数可返回你的结果,具体算法实现可用open primes命令打开primes函数文件看看。