首页 > 解决方案 > 如何从二维数组中找到素数?

问题描述

我需要在由随机数生成的二维数组中找到素数。我有两个函数函数 1 和函数 2。funtion1 负责在二维数组中查找素数,然后将素数保存到一维数组中,然后返回一维数组的大小。function1 负责打印一维数组。

function1 接受 2 个参数二维数组和一维数组。function2 接受 2 个参数数组和数组的大小。

#include <iostream>
#include <stdlib.h>     /* srand, rand */
#include <time.h> 
using namespace std;

int function1(int arrayA[][15],int arrayB[] );
void function2(int array[],int x);

int main(int argc, char** argv) {

    int myA[10][15];

    int myB[150];

    srand(time(NULL));

    for (int i = 0; i < 10; i++) // ...initialize it
    {
        for (int j = 0; j < 14; j++) {

            int row = rand() % 401 + 100;
            int column = rand() % 401 + 100;

            myA[i][j] = row, column;

            cout<< myA[i][j]<< " ";
        }
        cout<<endl; 
    }

    int x=function1(myA,myB);

    function2(myB,x);
}


int function1(int arrayA[][15],int arrayB[] ){

    for (int i = 0; i < 10; i++)                                //accessing two dimensional array row
    {                                                                       
        for (int j = 0; j < 15; j++) {                          //accesing two dimensional array column

            for(int prime=2;prime<arrayA[i][j];prime++){        //for prime control

                if(arrayA[i][j]%prime!=0){

                    for(int k=0;k<150;k++){                     //keeping arrayA`s prime numbers in arrayB
                        arrayB[k]=arrayA[i][j];
                    }
                }
            }   
        }
    }
    int sizeB=sizeof(arrayB)/sizeof(arrayB[0]);
return sizeB;
}   

void function2(int array[],int x){

    for(int i=0;i<x-1;i++){
        cout<<array[i];
    }
}

我对上面的解决方案进行了编码,但它只是打印随机生成的二维数组,但我真正需要的是随机生成的二维数组和该数组的素数(函数 2 的输出)我没有得到任何编译错误。

谢谢你!

标签: c++arraysmultidimensional-array

解决方案


函数 1 不会将素数添加到 arrayB。该数组将填充一个数字。所有 150 个位置都有一个不一定是素数的数字。最后的检查将是 2D 数组 % 中的最后一个数字(本身减一),它不会是 0。因此,所有 arrayB 都将是那个数字。

函数 1 应该总是返回 150。

函数2没有输出的原因是函数1访问了一个没有初始化的内存位置或者数组位置。所以不知道那个内存位置有什么。看看你是如何在 main 中填充 myA 的。

这段代码非常草率。你需要密切关注你在做什么。如果它在您的脑海中不起作用,那么在您编写代码时它也不会起作用。


推荐阅读