用matlab建立一个函数找1到N之间的素数,急!!!!!

来源:百度知道 编辑:UC知道 时间:2024/05/07 08:14:54
请教各位大侠,如何用matlab建立一个函数"findprime(N)",N为任意大于1的数,只要将其输入"findprime()",matlab就可以输出一个两列的答案,给出素数及它的序号:
1 2
2 3
3 5
4 7
5 11
....
速速赐教,万分感谢!!!!

MATLAB有现成函数 primes

Syntax:
p = primes(n)

Description:
p = primes(n) returns a row vector of the prime numbers less than or equal to n. A prime number is one that has no factors other than 1 and itself.

Examples:
p = primes(37)
The result is
p = 2 3 5 7 11 13 17 19 23 29 31 37

function r=findprime(n)
r=2:n;
for i=2:n;
if r(i-1)
r(2*i-1:i:end)=0;
end
end
r(r==0)=[];
r=[1:length(r);r].';
r(end)=n;