用matlab编写一个程序:求出200以内的质数,求!!!!急!!!!!

如题所述

% 主函数
function test()
x = [];
for i=1:200
flag = isprime(i);
if flag
x = [x,i];
end
end
disp('1-200之间的质数有:');
x
end

% 子函数
function out = isprime(n)
flag = 1;
for i=2:ceil(sqrt(n))
if mod(n,i)==0
flag = 0;
break;
end
end
out = flag;
end
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-04-21
matlab里有现成的
>> primes(200)

ans =

Columns 1 through 12

2 3 5 7 11 13 17 19 23 29 31 37

Columns 13 through 24

41 43 47 53 59 61 67 71 73 79 83 89

Columns 25 through 36

97 101 103 107 109 113 127 131 137 139 149 151

Columns 37 through 46

157 163 167 173 179 181 191 193 197 199

此外,isprime是用来判断是否为质数的,
>> isprime(201)

ans =

0
说明,201不是质数
>> factor(201)

ans =

3 67

%================================
>> type primes

function p = primes(n)
%PRIMES Generate list of prime numbers.
% PRIMES(N) is 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.
%
% Class support for input N:
% float: double, single
%
% See also FACTOR, ISPRIME.

% Copyright 1984-2004 The MathWorks, Inc.
% $Revision: 1.16.4.2 $ $Date: 2004/07/05 17:02:09 $

if length(n)~=1
error('MATLAB:primes:InputNotScalar', 'N must be a scalar');
end
if n < 2, p = zeros(1,0,class(n)); return, end
p = 1:2:n;
q = length(p);
p(1) = 2;
for k = 3:2:sqrt(n)
if p((k+1)/2)
p(((k*k+1)/2):k:q) = 0;
end
end
p = p(p>0);