เราได้รับอาร์เรย์ของจำนวนเต็ม งานคือการนับจำนวนคู่ในอาร์เรย์ที่สมาชิกหนึ่งหารอีกสมาชิกหนึ่งลงตัว
ตัวอย่าง
Input − int arr[] = {1, 2, 3, 6} Output − count is 4
คำอธิบาย − คู่ที่หารลงตัว: (1,2), (1,3), (1,6), (3,6) รวม 4 คู่
Input − int arr[] = {2, 5, 10} Output − count is 2
คำอธิบาย − คู่ที่หารลงตัว: (2,10), (5,10) รวม 2 คู่
แนวทางการแก้ปัญหา
- สร้างอาร์เรย์และคำนวณขนาด
- ใช้ลูปซ้อน i จาก 0 ถึง n-1, j จาก i+1 ถึง n-1
- ตรวจสอบว่า arr[i] % arr[j] == 0 หรือ arr[j] % arr[i] == 0
- ถ้าใช่เพิ่มตัวนับ
ตัวอย่างโค้ด C++
#include <iostream>
using namespace std;
int divisiblePairs(int a[], int size) {
int result = 0;
for (int i = 0; i < size; i++) {
for (int j = i + 1; j < size; j++) {
if (a[i] % a[j] == 0 || a[j] % a[i] == 0) {
result++;
}
}
}
return result;
}
int main() {
int a[] = {1, 4, 7, 8, 9};
int size = sizeof(a) / sizeof(a[0]);
cout << "count is " << divisiblePairs(a, size);
return 0;
}
ผลลัพธ์
count is 5
บทความนี้สาธิตการนับคู่ในอาร์เรย์ที่สมาชิกหนึ่งหารอีกสมาชิกหนึ่งลงตัว โดยใช้ลูปซ้อนตรวจสอบเงื่อนไขการหารลงตัวทั้งสองทาง