Cho danh sách n số và một số. Nhiệm vụ: kiểm tra số đó có chia hết cho mọi phần tử trong danh sách không.
Ví dụ:
Đầu vào: list[] = [4, 10, 6, 5, 9], num = 5
Đầu ra: No
Giải thích: 4, 6, 9 không chia hết cho 5.
Phương pháp giải
Duyệt danh sách, nếu bất kỳ phần tử nào không chia hết cho num => false. Ngược lại true.
Chương trình minh họa
Ví dụ
#include <iostream>
using namespace std;
bool isListDivNum(int list[], int num, int size) {
for (int i = 0; i < size; i++) {
if (list[i] % num != 0)
return false;
}
return true;
}
int main() {
int list[] = {762, 9, 123, 99};
int num = 3;
int size = (sizeof(list) / sizeof(list[0]));
if (isListDivNum(list, num, size))
cout << "All elements of the list are divisible by number";
else
cout << "All elements of the list are not divisible by number";
return 0;
}
Kết quả
All elements of the list are divisible by number