ในส่วนนี้เราจะดูว่าอาร์เรย์หนึ่งมีตัวเลข n หรือไม่ เราต้องตรวจสอบว่าเราสร้างตัวเลขโดยใช้องค์ประกอบทั้งหมดของตัวเลขเหล่านี้หรือไม่ ตัวเลขนั้นจะหารด้วย 3 ลงตัวหรือไม่ หากองค์ประกอบอาร์เรย์คือ {15, 24, 23, 13} เราก็สามารถสร้างจำนวนเต็มได้ เช่น 15242313 ซึ่งจะหารด้วย 3 ลงตัว
อัลกอริทึม
checkDivThree(arr)
Begin rem := 0 for each element e in arr, do rem := (rem + e) mod 3 done if rem is 0, then return true end if return false End
ตัวอย่าง
#include<iostream>
#define MAX 4
using namespace std;
bool checkDivThree(int arr[], int n){
int rem = 0;
for(int i = 0; i<n; i++){
rem = (rem + arr[i]) % 3;
}
if(rem == 0){
return true;
}
return false;
}
main() {
int arr[] = {15, 24, 23, 13};
int n = sizeof(arr)/sizeof(arr[0]);
if(checkDivThree(arr, n)){
cout << "Divisible";
}else{
cout << "Not Divisible";
}
} ผลลัพธ์
Divisible