C++中统计至少能被另一个数组中的一个元素整除的元素个数
我们有两个数组,假设为arr_1[]和arr_2[],两者都包含整数值,任务是计算至少能被另一个数组中的一个元素整除的元素个数。这意味着我们需要统计在第二个数组arr_2中至少有一个因子的元素。
数组是一种数据结构,可以存储相同类型元素的固定大小的顺序集合。数组用于存储数据集合,但通常将数组视为相同类型变量的集合更有用。
例如
Input − int arr_1[] = {1, 2, 3, 4, 5}
arr_2[] = {2, 6, 12, 15}
Output − count is 2说明 − arr_1[]中有5个元素,arr_2[]中有4个元素。arr_1[]中的所有元素都能被arr_2[]中的元素整除。所以计数是5。
Input − int arr_1[] = {1, 2, 3, 4, 5}
arr_2[] = {13, 11}
Output − count is 0说明 − arr_1[]中有5个元素,arr_2[]中有2个元素。arr_1[]中的任何元素都不能被arr_2[]中的元素整除。所以计数是0。
下面程序中使用的方法如下
创建两个数组,例如arr_1[]和arr_2[]
使用length()函数计算两个数组的长度,该函数将根据数组中的元素返回整数值。
取一个临时变量来存储元素的计数。
创建一个无序集合变量,例如us
开始循环,i从0开始,i小于第二个数组的大小。
在循环内,将arr_2[i]插入到us中。
开始另一个循环,i从0开始,i小于第一个数组的大小。
在循环内,开始另一个循环,j从1开始,j*j <= arr_1[i]
在此处检查,如果arr_1[i]%j == 0,则检查us.find(j)!=us.end() 或 us.find(arr_1[i]/j) != us.end(),如果是,则将计数加1
否则,中断循环
返回计数
打印结果。
示例
#include <iostream>
#include <unordered_set>
using namespace std;
// Function to count the number of elements
// in first array whose atleast one factor is
// present in the second array
int totalelements(int arr_1[], int size1, int arr_2[], int size2){
// variable 'result' to count the number of elements
int result = 0;
// Hash of second array elements
unordered_set<int> h;
for (int i = 0; i < size2; i++){
h.insert(arr_2[i]);
}
// traverse through array elements
// and find its factors
for (int i = 0; i < size1; i++){
for (int j = 1; j * j <= arr_1[i]; j++){
if (arr_1[i] % j == 0){
// check if the factor is present in
// second array using the h
if ((h.find(j) != h.end()) || (h.find(arr_1[i] / j)!= h.end())){
result++;
break;
}
}
}
}
return result;
}
// Main function
int main(){
int arr_1[] = { 1, 2, 3, 4, 5 };
int arr_2[] = { 2, 6, 12, 15 };
int size1 = sizeof(arr_1) / sizeof(arr_1[0]);
int size2 = sizeof(arr_2) / sizeof(arr_2[0]);
cout <<"count is "<<totalelements(arr_1, size1, arr_2, size2);
return 0;
}输出
如果我们运行上面的代码,我们将得到以下输出:
count is 2
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP