7-5 判断素数 (10分)
本题的目标很简单,就是判断一个给定的正整数是否素数。
输入格式:
输入在第一行给出一个正整数N(≤ 10),随后N行,每行给出一个小于2
31
的需要判断的正整数。
输出格式:
对每个需要判断的正整数,如果它是素数,则在一行中输出Yes,否则输出No。
输入样例:
2
11
111
输出样例:
Yes
No
#include<stdio.h>
#include<math.h>
int pdss(int n)//1-素数
{int c=1;
if(n==1)c=0;
else
{ for(int j=2;j<=sqrt(n);j++)
{
if(n%j==0)
{c=0;
break;
}
}
}
return c;
}
main(){
int a,b[10];
scanf("%d",&a);
for(int j=0;j<a;j++){
scanf("%d",&b[j]);
}
for(int j=0;j<a;j++){
int c=pdss(b[j]);
if(c==1){printf("Yes\n");}
else if(c==0){ printf("No\n");}
}
return 0;
}
#include<stdio.h>
#include<math.h>
int pdss(int n){
int c=1;
if(n==1){c=0;}
// else if(n==2){c=1;}
else for(int j=2;j<sqrt(n);j++)
{
if(n%j==0)
{c=0;
break;}
}
return c;
}
main(){
int a,b[10];
scanf("%d",&a);
for(int j=0;j<a;j++){
scanf("%d",&b[j]);
}
for(int j=0;j<a;j++){
int c=pdss(b[j]);
if(c==1){printf("Yes\n");}
else if(c==0){ printf("No\n");}
}
return 0;
}
本文介绍了一个简单的算法,用于判断一个给定的正整数是否为素数。通过输入多个待判断的整数,程序将输出每个数是否为素数的结果。算法首先检查数字是否等于1,如果是,则直接返回非素数;否则,程序会遍历从2到该数平方根的所有整数,检查是否存在除数,从而确定该数是否为素数。
1577

被折叠的 条评论
为什么被折叠?



