โจทย์
ได้รับลิสต์ตัวเลขและตัวเลข num ทางเราต้อง ตรวจสอบว่า num หารทุกตัวในลิสต์ลงตัวหรือไม่
ตัวอย่าง
Input: list[] = {4, 10, 6, 5, 9}, num = 5
Output: No (4,6,9 หาร 5 ไม่ลงตัว)
แนวทางแก้ปัญหา
วนลูปตรวจสอบ list[i] % num == 0 สำหรับทุก i ถ้ามีตัวใดไม่หารลงตัว คืน false ทันที
โปรแกรมตัวอย่าง
#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;
}
ผลลัพธ์
All elements of the list are divisible by number