PASCAL求出100以内的全部素数,并按每行五个数显示

来源:学生作业帮助网 编辑:作业帮 时间:2024/04/29 01:47:35
PASCAL求出100以内的全部素数,并按每行五个数显示

PASCAL求出100以内的全部素数,并按每行五个数显示
PASCAL求出100以内的全部素数,并按每行五个数显示

PASCAL求出100以内的全部素数,并按每行五个数显示
输入n
输出为1~n的素数,每五个一行
var
i,j,count,n:longint;//i,j为循环变量;count为计数器,每满五则换行并清零;n为输入的数;
f:boolean;//判断是否为素数的变量;
begin
readln(n);//读入
for i:=2 to n do//外循环,枚举从2到n的数,由于1比较特殊,所以从2枚举.
begin
f:=true;//判断量先设为true;
for j:=2 to trunc(sqrt(i)) do//枚举从2 到 根号i取整的数,这样可以有效节约时间复杂度;
if i mod j =0 then f:=false;如果在2~n之间有能整除i的数则将判断量设为false;
if f then//如果i为素数
begin
write(i,' ');//输出i;
inc(count);//给计数器加一;
if count=5 then begin writeln;count:=0;end;//如果计数器满五则清零并换行;
end;//end if;
end;//end for i;
end.//end program;
下面是输入为100的输出结果:
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
如果要求每行末尾不能有空格,那么把if f then 后面改为下面:
if f then
begin
inc(count);
if count=5 then begin count:=0;writeln(i);end
else write(i,' ');
end;
最后,还请给个最佳吧~