matlab 编写一个函数文件 检测一个数是否是素数,若是素数则输出为0否则输出1

 我来答
jimtien
推荐于2018-04-05 · TA获得超过7654个赞
知道大有可为答主
回答量:2146
采纳率:88%
帮助的人:1137万
展开全部
function f= is_prime(n)
    f = 1;
    n = uint16(n);
    if n<= 1
            return;
        else
            if n<=3
               f = 0;
               return;
            end
        end
        
        if( mod(n,2) ==0 || mod(n,3) ==0 )
           return;                
        end            
        i = 5;
        while(i*i<=n)
             if ( mod(n,i)== 0 || mod(n,i+2) == 0 )
                 return;
             end
            i = i + 6;
    end
    f = 0;   
end


测试一下这个函数,来找出1000以内的素数

clear all;
tic;
for i=1:1000
    if is_prime(i)==0
        fprintf('%d,',i);
    end    
end
fprintf('\n');
toc;


结果:

>> test_is_prime

2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997,

Elapsed time is 0.016410 seconds.

推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式