你好我写这个函数来打印2d数组时的素数,当我输入例如1 2 3 4 5 6 7 8它打印1 2 3 5 7我怎么能编辑它不
将您的外部if
声明更改为
if (count == 0 && o[i][j] != 1) {
c[I] = o[i][j];
I++;
p++;
}
编写一个检查数字是否为素数的函数会更容易,并为每个矩阵元素调用该函数。还有更有效的方法来确定数字是否为素数。
我添加了一些注释来解释发生了什么,但事先,你将忽略结果列表中的'1',所以我添加了“if(o [i] [j]!= 1)”,在另一个中手,找到主要列表,如果第一个数字是可分的,你将不需要计算其他数字,所以你可以添加“休息”;在for(...)
void FindPrime(int o[5][5]){
int c[100];int I=0 ,count=0,p =0;
int i,j,h;
for(i =0;i<5;i++)
{
for(j =0;j<5;j++)
{
count =0;
for(int k =2;k<o[i][j];k++)
{
if(o[i][j]% k == 0)
{
if(o[i][j]!=1)// Do not add 1 to the array
{
count++;
// To make the function faster you can add "break;" here. If find the first dividable number, don't continue for
}
}
}
if(count == 0)
{
c[I] = o[i][j];
I++;
p++;
}
}
}
for(int I =0;I<p;I++)
{
h=c[I];
cout<<" "<< h <<" ";
}
cout<<"\n\n";
}