用 C++ 统计数组中可被 k 整除的元素个数


给定一个正整数数组和一个整数变量 k。任务是计算数组中可被给定值 k 整除的元素个数。

输入 − int arr[] = {4, 2, 6, 1, 3, 8, 10, 9}, k = 2

输出 − 数组中可被 2 整除的元素个数为 - 5

解释 − 我们将数组中的元素除以值 k 并检查余数是否为 0。因此,4 可被 2 整除,2 可被 2 整除,6 可被 2 整除,1 不可被 2 整除,3 不可被 2 整除,8 可被 2 整除,10 可被 2 整除,9 不可被 2 整除。因此,数组中有 5 个元素完全可被 k(即 2)整除。

输入 − int arr[] = {3, 2, 9, 15, 0, 8, 10}, k = 3

输出 − 数组中可被 3 整除的元素个数为 - 3

解释 − 我们将数组中的元素除以值 k 并检查余数是否为 0。因此,3 可被 3 整除,2 不可被 3 整除,9 可被 3 整除,15 可被 3 整除,0 不可被任何数整除,8 不可被 3 整除,10 不可被 3 整除。因此,数组中有 3 个元素完全可被 k(即 3)整除。

下面程序中使用的算法如下

解决特定问题可能有多种方法。因此,我们首先采用一种朴素的方法。

  • 输入一个整数元素数组和一个整数变量 k

  • 计算数组的长度并将数据传递给函数以进行进一步处理。

  • 取一个临时变量 count 来存储可被 k 整除的元素的个数

  • 从 0 开始循环 FOR 到数组的长度

  • 在循环内部,检查 IF arr[i] % k = 0 则将 count 加 1

  • 返回 count

  • 打印结果。

高效方法

  • 将元素输入到整数类型的向量中,并取一个整数变量 k。

  • 取一个临时变量 count 来存储可被 k 整除的元素的个数

  • 将 count 设置为对内置 count_if() 函数的调用,该函数将 vector.begin()、vector.end() 作为参数并开始遍历,然后返回 i%k 是否为 0。

  • 打印结果。

示例(朴素方法)

 实时演示

#include <bits/stdc++.h>
using namespace std;
int divisible_k(int arr[], int size, int k){
   int count = 0;
   for(int i = 0; i<size; i++){
      if(arr[i]%k==0){
         count++;
      }
   }
   return count;
}
int main(){
   int arr[] = {4, 2, 6, 1, 3, 8, 10, 9};
   int k = 2;
   int size = sizeof(arr) / sizeof(arr[0]);
   cout<<"Count the number of elements in an array which are divisible by "<<k<<" are: "<<divisible_k(arr, size, k);
   return 0;
}

输出

如果我们运行以上代码,它将生成以下输出:

Count the number of elements in an array which are divisible by 2 are: 5

示例(高效方法)

 实时演示

#include <bits/stdc++.h>
using namespace std;
int main(){
   vector<int> vec = {4, 2, 6, 1, 3, 8, 10, 9};
   int count = count_if(vec.begin(), vec.end(), [](int i, int k = 2) { return i % k == 0; });
   cout<<"Count the number of elements in an array which are divisible by k are: "<<count;
   return 0;
}

输出

如果我们运行以上代码,它将生成以下输出:

Count the number of elements in an array which are divisible by 2 are: 5

更新于: 2020-11-02

1K+ 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.