从XJOI P1174到is_prime

从XJOI P1174到is_prime

判断质数

时间:1s 空间:256M

题目描述:

质数是数论的宠儿,也称作素数,一个数是质数,意味着它只能被1和它本身整除。比如前几个质数是2,3,5,7,11,13,17,现在给你一个整数n, 判断它是否是素数。

输入格式:

第一行输入一个整数T,表示需要判断的数的个数

接下来T行每行一个整数n,表示需要判断的数。

输出格式:

输出T行,判断是否是素数。是,输出“Yes”,否则输出“No”

样例输入:

2 1 2

样例输出:

No Yes

约定:

1<=n<=105,1<=T<=10

提示:

要注意,这题需要用循环输入T个整数。

program XJOIp1174(input,output);
var
 t,j,n:longint;
function is_prime(var n:longint):boolean;
var
 i:longint;
begin
 is_prime:=false;
 if n<2 then exit(false);
 if n=2 then exit(true)
 else if n=3 then exit(true)
 else if n=4 then exit(false)
 else if n=5 then exit(true)
 else
 begin
  for i:=2 to trunc(sqrt(n)) do
  if n mod i=0 then exit(false)
 end;
 exit(true);
end;
begin
 readln(t);
 for j:=1 to t do
 begin
  readln(n);
  if is_prime(n)=true then writeln('Yes')
  else writeln('No');
 end;
end.

着重分析这里:

function is_prime(var n:longint):boolean;
var
 i:longint;
begin
 is_prime:=false;
 if n<2 then exit(false);
 if n=2 then exit(true)
 else if n=3 then exit(true)
 else if n=4 then exit(false)
 else if n=5 then exit(true)
 else
 begin
  for i:=2 to trunc(sqrt(n)) do
  if n mod i=0 then exit(false)
 end;
 exit(true);
end;