matlab 求素数(四种方法)(精)

法一:

clc;
clear;
m = linspace(1,100,100)
flag = 0;
res = 0;
for i = 3:length(m)
    for j = 2:i-1
        if mod(m(i),j) == 0
            flag = 1;
            break;
        else 
            flag = 0;
        end
    end
    if flag == 0
        r = [res,m(i)];
        res = r;
    end
end
r(2:length(r))

法二(数据较大时挺好用,且代码简单)

clear
close all
clc
tic
x = [1:2:100000];
index = isprime(x);
x(~index)= []
toc

法三(数据量小时很快)

clear
close all
clc
tic
isPrime_num = 0;   
prime=[2 3];     
for i=2:100000
    for j=2:fix(i/2)
        if mod(i,j)==0
            isPrime_num=0;     
            break;    
        else 
            isPrime_num = 1;
        end
    end
    if isPrime_num == 1          
        prime=[prime,i];
    end
end
prime
toc

法四:

m = input ('Input a number ')
for i = 3:2:m
    for p = 2:2:i
        if rem(i,p) == 0
            break;
        else
            p=p+1;
        end
        if p == i
            disp(i);
        end
    end
    i=i+1;
end

你可能感兴趣的:(❥matlab)