用随机两数产生 10个互不相同两位整数存放到一维数组中,并输出其中的素数
时间: 2024-03-02 07:49:32 浏览: 33
可以使用类似上面的方法生成两位整数,然后判断是否互不相同并且是否是素数,将符合条件的数存放到数组中。以下是示例代码:
```c++
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cmath>
using namespace std;
bool isPrime(int num)
{
if (num < 2) {
return false;
}
for (int i = 2; i <= sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
int main()
{
const int N = 10;
int arr[N];
srand(time(0));
int count = 0;
while (count < N) {
int num1 = rand() % 90 + 10;
int num2 = rand() % 90 + 10;
int num = num1 * 100 + num2;
bool isDup = false;
for (int i = 0; i < count; i++) {
if (arr[i] == num) {
isDup = true;
break;
}
}
if (!isDup && isPrime(num)) {
arr[count++] = num;
}
}
cout << "生成的素数数组是:" << endl;
for (int i = 0; i < N; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
```
其中,isPrime() 函数用来判断一个数是否是素数,% 90 + 10 可以将生成的两位数限制在 10 到 99 之间。如果生成的数不重复并且是素数,就存放到数组中。最后遍历数组输出素数。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)