MATLAB爱好者论坛-LabFans.com

MATLAB爱好者论坛-LabFans.com (https://www.labfans.com/bbs/index.php)
-   MATLAB论坛 (https://www.labfans.com/bbs/forumdisplay.php?f=6)
-   -   求助:编写一个找出所有质数的方程 (https://www.labfans.com/bbs/showthread.php?t=9839)

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函数文件看看。


所有时间均为北京时间。现在的时间是 03:17

Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.