20.建立一个矩阵类 Array,对二维数组中左下三角的全部元素(包括对角线上的元素)作如下变换:(1)若该数不是素数则保持不变;(2)若该数是素数,则用大于它的最小素数替换该数。并统计二维数组中左下三角的全部元素(包括对角线上的元素)中的素数个数。要求如下:
- 私有数据成员
- int x[4][4];存储需要处理二维数组的各元素值
- int count;存储左下三角元素中素数的个数。
- 公有成员函数
- 构造函数:进行初始化x数组并将count初始化为0。
- int fun(int);判断一个数是否为素数的函数。
- int encode( );对x数组中左下三角的全部元素(包括对角线上的元素)逐一进行判断,若该数不是素数则保持不变,若该数是素数,则用大于它的最小素数替换该数,并返回素数的个数。
- void print():按行输出矩阵的值。
- 编写一个程序测试类,声明Array对象A,将一个矩阵存入对象A中,并输出矩阵的值,使用以下测试数据:
int a[4][4] = {{3, 6, 4, 17}, {8, 5, 9, 10}, {12, 19, 7, 20}, {4, 14, 21, 23}};
3 6 4 17
8 5 9 10
12 19 7 20
4 14 21 23
变换后的矩阵为
5 6 4 17
8 7 9 10
12 23 11 20
4 14 21 29
count=5
#include<iostream>
#include<iomanip>
using namespace std;
class Array{
int x[4][4];
int count;
public:
Array(int (*a)[4]){
count=0;
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
x[i][j]=a[i][j];
}
}
}
int encode(){
for(int i=0;i<4;i++){
for(int j=0;j<i+1;j++){
if(fun(x[i][j])){
count++;
while(!fun(++x[i][j]));
}
}
}
return count;
}
int fun(int n){
if(n==0||n==1)return 0;
for(int i=2;i<n;i++){
if(n%i==0)return 0;
}
return 1;
}
void print(){
for(int i=0;i<4;i++){
for(int j=0;j<4;j++)cout<<setw(3)<<x[i][j];
cout<<endl;
}
}
};
int main(){
int a[4][4] = {{3, 6, 4, 17}, {8, 5, 9, 10}, {12, 19, 7, 20}, {4, 14, 21, 23}};
Array arr(a);
arr.print();
cout<<"count="<<arr.encode()<<endl;
arr.print();
return 0;
}
#include <iostream>
using namespace std;
class Array
{
int x[4][4], count;
public:
Array(int (*a)[4], int n)
{
count = 0;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
x[i][j] = a[i][j];
if (fun(x[i][j]))count++;
}
}
}
int encode()
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < i + 1; j++)
{
if (fun(x[i][j]))
{
int k = x[i][j] + 1;
while (!fun(k))
{
k++;
}
x[i][j] = k;
}
}
}
return 0;
}
int fun(int e)
{
if (e < 2)
return 0;
for (int i = 2; i < e; i++)
if (e % i == 0)
return 0;
return 1;
}
void print()
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
cout << x[i][j] << " ";
}
cout << endl;
}
}
};
int main()
{
int a[4][4] = {{3, 6, 4, 17}, {8, 5, 9, 10}, {12, 19, 7, 20}, {4, 14, 21, 23}};
Array arr(a, 4);
arr.print();
arr.encode();
arr.print();
system("pause");
return 0;
}