您好,如何防止此函数使用质数数组打印 1

Hello how to prevent this func from print 1 with the prime numbers array

本文关键字:数数 数组 打印 何防止 函数 您好      更新时间:2023-10-16

你好,我写这个函数来打印 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<<"nn";
}