用 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
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP