Free Pascal中求1~100的素数有几个?怎么编?、

2025-05-09 06:05:49
推荐回答(5个)
回答1:

Program exp;

var p:array[1..1000] of longint;
i,ans:longint;

function prime(n:longint):boolean;
var i:longint;
f:boolean;
begin
f:=true;
for i:=2 to trunc(sqrt(n)) do
if n mod i=0 then
begin
f:=false;
break;
end;
prime:=f;
end;

begin
ans:=0;
for i:=2 to 1000 do
if prime(i) then
begin
inc(ans);
p[ans]:=i;
end;
writeln(ans);
for i:=1 to ans-1 do write(p[i],' ');
writeln(p[ans]);
end.

如果还没有学过函数看下面的:

Program exp;

var p:array[1..1000] of longint;
i,j,ans:longint;
f:boolean;

begin
ans:=0;
for i:=2 to 1000 do
begin
f:=true;
for j:=2 to trunc(sqrt(i)) do
if i mod j=0 then
begin
f:=false;
break;
end;
if f then
begin
inc(ans);
p[ans]:=i;
end;
end;
writeln(ans);
for i:=1 to ans-1 do write(p[i],' ');
writeln(p[ans]);
end.

你的程序里有for b:=1 to a do一句,但是b不能达到a,因为当b=a的时候,a mod b=0,那么a本来是素数就被你判成不是素数了,b也不能是1因为当b=1的时候a mod b=0。
所以一般判断素数是for b:=2 to a-1 do,效率更高的是for b:=2 to a div 2 do,效率最高的是
for b:=2 to trunc(sqrt(a)) do,就是到a的平方根,这是有严格证明的。

回答2:

program ex1;
var a,b,t:integer;
begin
t:=0;
for a:=1 to 100 do
for b:=1 to a do
if a mod b=0 then
begin
t:=t+1;
if t<=2 then writeln(a:2);
end;
end.

这是我前天写的,这个是竖的打出来的,我也才学一周不到,自学,不知道怎么每行打出5个换行,正在研究。。。

回答3:

program ex1;
var a,b,t:integer;
bb:boolean;
begin
t:=1;
for a:=3 to 100 do
begin
bb:=true;
for b:=2 to trunc(sqrt(a)) do
if a mod b=0 then bb:=false;
if bb=true then t:=t+1;
end;
write(t);
readln;
end.
你的程序缺少了一个布尔型的变量,而且1不是素数,但2是素数,所以第一层循环应该从3开始,而总量也应该增加1.第二层循环应该从2开始,应为任何自然数都能除的尽1.

回答4:

var
i,j,m,n,s:longint;
function ss(x:longint):boolean;
var
i:longint;
begin
ss:=true;
for i:=2 to trunc(sqrt(x)) do
begin
if x mod i=0 then
begin
ss:=false;
break;
end;
end;
end;
begin
readln(n);
for i:=2 to n do
begin
if ss(i) then inc(s);
end;
writeln(s);
end.

回答5:

var
a:array[1..100] of longint;
i,j,r:longint;
begin
for i:=1 to 100 do
begin
for j:=1 to i do
if i mod j=0 then
begin
t:=t+1;
if t=2 then begin
for r:=1 to 100 do
begin
a[r]:=t;
write(a[r]);
if r mod 5=0 then writeln;
end;
end;
end;
end.