SAS中文论坛

标题: 找到1000以内的素数 [打印本页]

作者: shiyiming    时间: 2003-10-3 01:00
标题: 找到1000以内的素数
/*这是最经典的算法*/
data prime(keep=i);
i=2;output;
i=3;output;
do i=2 to 1000;
do j=2 to int(sqrt(i));
if mod(i,j)=0 then leave;
else if j=int(sqrt(i)) then output;
end;
end;
run;
作者: shiyiming    时间: 2003-10-4 02:37
Another method:

data prime(keep=i);
do i=2 to 1000;
do j=2 to 1000;
if mod(i,j)=0 and i^=j  then isprime=0;
end;
if isprime^=0 then output;
isprime=1;
end;
proc print;
run;
作者: shiyiming    时间: 2008-1-26 23:55
标题: Re: 找到1000以内的素数
shiyiming提供的这个算法是比较快,在一般C++的书上提到求素数的算法,好像用这个的比较多。如果可以用机器性能换算法效率,下面的代码可能可读性会更强些:
[code:asu6zl7n]data prime(keep=x);
        do x=2 to 1000 by 1;
                   do i=2 to x by 1 while (mod(x,i)^=0);
                   end;
           if i=x then output;
        end;
run;[/code:asu6zl7n]




欢迎光临 SAS中文论坛 (https://mysas.net/forum/) Powered by Discuz! X3.2